Android hotspot wifi java

Use java code to enable portable wi-fi hotspot

currently I am building a very small native app for my android phone. I want to active the portable wi-fi hotspot when I click one button in the app. But I didn’t know how to invoke Android API to active portable wi-fi hotspot. I know how to do it through the UI. Can anyone show me?

1 Answer 1

// code to enable portable wifi hotspot public void EnableWifiHotspot() < try< WifiManager wifi_manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); WifiConfiguration wifi_configuration = null; Method wifiHotspotEnabledMethod=wifi_manager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); wifiHotspotEnabledMethod.invoke(wifi_manager, wifi_configuration, true); >catch (NoSuchMethodException e) < e.printStackTrace(); >catch (IllegalArgumentException e) < e.printStackTrace(); >catch (IllegalAccessException e) < e.printStackTrace(); >catch (InvocationTargetException e) < e.printStackTrace(); >> //code for disabling portable wifi hotspot public void DisableWifiHotspot() < try< WifiManager wifi_manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); WifiConfiguration wifi_configuration = null; Method wifiHotspotEnabledMethod=wifi_manager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); wifiHotspotEnabledMethod.invoke(wifi_manager, wifi_configuration, false); >catch (NoSuchMethodException e) < e.printStackTrace(); >catch (IllegalArgumentException e) < e.printStackTrace(); >catch (IllegalAccessException e) < e.printStackTrace(); >catch (InvocationTargetException e) < e.printStackTrace(); >> 

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo)

When I execute above method in Android 8.0, I am getting below statement in logcat.

com.gck.dummy W/WifiManager: com.gck.dummy attempted call to setWifiApEnabled: enabled = true 

is it possible that they removed this way of doing it in Android O? Turning on the wifi hotspot isn’t part of the Android sdk. So this way that’s been going around using reflection is somewhat hacky

3 Answers 3

I thought the LocalOnlyHotspot route was the way to, but as @edsappfactory.com said in the comments — it only gives closed network, no internet access.

In Oreo hot-spotting/tethering moved to ConnectionManager , and its annotated @SystemApi , so (nominally) inaccessible.

Читайте также:  Аэропорт храброво вай фай пароль

As part of something else I was doing, I made an app and put it on github here. It uses reflection to get at the function and DexMaker to generate a subclass of ConnectionManager.OnStartTetheringCallback (which is also inaccessible).

Think it all works okay — bit rough around the edges, so please feel free to make better!

Relevant bits of code are in:

I lost patience trying to get my DexMaker-generated callback to fire the MyOnStartTetheringCallback so all that code is in disarray and commented out.

@AnujJPandey somebody else actually asked me that on GitHub recently. You would have to find where they moved methods for changing those settings in the Android code and maybe try using Reflection. Do not think its in ConnectionManager . Sorry can’t be much more help.

@Jon thanks for reverting, I found the solution and thanks again for such awesome work, on reflection. keep it up.

@anujjpandey Great. Any chance you could put your solution somewhere — in a Gist or GitHub so I can point ppl towards it next time I’m asked? Could commit to my original gitgub code if that easier.

Finally I got the solution. Android 8.0, they provided public api to turn on/off hotspot. WifiManager

Below is the code to turn on hotspot

private WifiManager.LocalOnlyHotspotReservation mReservation; @RequiresApi(api = Build.VERSION_CODES.O) private void turnOnHotspot() < WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() < @Override public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) < super.onStarted(reservation); Log.d(TAG, "Wifi Hotspot is on now"); mReservation = reservation; >@Override public void onStopped() < super.onStopped(); Log.d(TAG, "onStopped: "); >@Override public void onFailed(int reason) < super.onFailed(reason); Log.d(TAG, "onFailed: "); >>, new Handler()); > private void turnOffHotspot() < if (mReservation != null) < mReservation.close(); >> 

onStarted(WifiManager.LocalOnlyHotspotReservation reservation) method will be called if hotspot is turned on.. Using WifiManager.LocalOnlyHotspotReservation reference you call close() method to turn off hotspot.

Note: To turn on hotspot, the Location(GPS) should be enabled in the device. Otherwise, it will throw SecurityException

Источник

Android: Programmatically Turn on WiFi hotspot

I am trying to turn on the portable Wifi hotspot ON, by referring this link:
how to set advanced settings of android wifihotspot This is working well on Samsung Galaxy S3 Android v4.4.2.(no issues)
But on other devices with the same or lower Android version, the application crashes and restarts the device.

package com.android.startwifi; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.app.Activity; import android.content.Context; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class Main extends Activity < public WifiManager wifiManager; public Context context; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i("hi1","hi"); createWifiAccessPoint(); >private void createWifiAccessPoint() < WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE); if(wifiManager.isWifiEnabled()) < wifiManager.setWifiEnabled(false); >Method[] wmMethods = wifiManager.getClass().getDeclaredMethods(); boolean methodFound=false; for(Method method: wmMethods)< if(method.getName().equals("setWifiApEnabled"))< methodFound=true; WifiConfiguration netConfig = new WifiConfiguration(); netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); try < boolean apstatus=(Boolean) method.invoke(wifiManager, netConfig,true); //statusView.setText("Creating a Wi-Fi Network \""+netConfig.SSID+"\""); for (Method isWifiApEnabledmethod: wmMethods) < if(isWifiApEnabledmethod.getName().equals("isWifiApEnabled"))< while(!(Boolean)isWifiApEnabledmethod.invoke(wifiManager))< >; for(Method method1: wmMethods) < if(method1.getName().equals("getWifiApState"))< int apstate; apstate=(Integer)method1.invoke(wifiManager); // netConfig=(WifiConfiguration)method1.invoke(wifi); //statusView.append("\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n"); >> > > if(apstatus) < System.out.println("SUCCESSdddd"); //statusView.append("\nAccess Point Created!"); //finish(); //Intent searchSensorsIntent = new Intent(this,SearchSensors.class); //startActivity(searchSensorsIntent); >else < System.out.println("FAILED"); //statusView.append("\nAccess Point Creation failed!"); >> catch (IllegalArgumentException e) < e.printStackTrace(); >catch (IllegalAccessException e) < e.printStackTrace(); >catch (InvocationTargetException e) < e.printStackTrace(); >> > if(!methodFound) < //statusView.setText("Your phone's API does not contain setWifiApEnabled method to configure an access point"); >> @Override public boolean onCreateOptionsMenu(Menu menu) < // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; >@Override public boolean onOptionsItemSelected(MenuItem item) < // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int if (id == R.id.action_settings) < return true; >return super.onOptionsItemSelected(item); > > 
09-10 18:35:01.644: D/jdwp(29752): prepping for JDWP over ADB 09-10 18:35:01.644: D/jdwp(29752): ADB transport startup 09-10 18:35:01.644: D/dalvikvm(29752): Elevating priority from 0 to -8 09-10 18:35:01.645: D/jdwp(29752): JDWP: thread running 09-10 18:35:01.645: D/jdwp(29752): acceptConnection 09-10 18:35:01.646: D/jdwp(29752): trying to receive file descriptor from ADB 09-10 18:35:01.646: D/dalvikvm(29752): zygote get thread init done 09-10 18:35:01.653: D/jdwp(29752): received file descriptor 34 from ADB 09-10 18:35:01.658: D/jdwp(29752): processIncoming 09-10 18:35:01.659: D/jdwp(29752): processIncoming 09-10 18:35:01.659: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, flags=0x0, dataLen=0x8 09-10 18:35:01.661: D/jdwp(29752): processIncoming 09-10 18:35:01.661: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x17, flags=0x0, dataLen=0xC 09-10 18:35:01.663: D/jdwp(29752): processIncoming 09-10 18:35:01.663: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, flags=0x0, dataLen=0x8 09-10 18:35:01.665: D/jdwp(29752): processIncoming 09-10 18:35:01.665: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, flags=0x0, dataLen=0x8 09-10 18:35:01.676: D/jdwp(29752): sendBufferedRequest : len=0x3D 09-10 18:35:01.736: D/jdwp(29752): sendBufferedRequest : len=0x45 09-10 18:35:01.754: W/asset(29752): AssetManager-->addDefaultAssets CIP path not exsit! 09-10 18:35:02.219: I/hi1(29752): hi 09-10 18:35:02.261: D/WifiManager(29752): Enter init, sThreadRefCount:0 09-10 18:35:02.268: D/WifiManager(29752): Create WifiManager handlerthread 09-10 18:35:03.599: I/System.out(29752): SUCCESSdddd 09-10 18:35:03.634: V/PhoneWindow(29752): DecorView setVisiblity: visibility = 4 09-10 18:35:03.745: V/PhoneWindow(29752): DecorView setVisiblity: visibility = 0 09-10 18:35:03.922: D/libEGL(29752): loaded /system/lib/egl/libEGL_mali.so 09-10 18:35:03.924: D/libEGL(29752): loaded /system/lib/egl/libGLESv1_CM_mali.so 09-10 18:35:03.927: D/libEGL(29752): loaded /system/lib/egl/libGLESv2_mali.so 09-10 18:35:04.111: D/OpenGLRenderer(29752): Enabling debug mode 0 09-10 18:35:10.610: E/InputEventReceiver(29752): channel '41f21f48 com.android.startwifi/com.android.startwifi.Main (client)' ~ Publisher closed input channel or an error occurred. events=0x9 
  • I would like to know why is this app behaving normally on Samsung S3 but not on other devices?
  • How can I fix this issue?
Читайте также:  Wi fi режим инфраструктура

Источник

How to create wifi tethering Hotspot in Android Marshmallow?

I was working in Android Marshmallow and have found a way to create WiFi tethering as describe below. Note that according to Android 6.0 Changes Your apps can now change the state of WifiConfiguration objects only if you created these objects. And beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. Read this article to know more about this. I can see you are creating Hotspot by your own. So no issue. The permission in Manifest is given below:

I am using the following function to create WiFi tethering Hotspot in android marshmallow:

public void setWifiTetheringEnabled(boolean enable) < //Log.d(TAG,"setWifiTetheringEnabled: "+enable); String SSID=getHotspotName(); // my function is to get a predefined SSID String PASS=getHotspotPassword(); // my function is to get a predefined a Password WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); if(enable)< wifiManager.setWifiEnabled(!enable); // Disable all existing WiFi Network >else < if(!wifiManager.isWifiEnabled()) wifiManager.setWifiEnabled(!enable); >Method[] methods = wifiManager.getClass().getDeclaredMethods(); for (Method method : methods) < if (method.getName().equals("setWifiApEnabled")) < WifiConfiguration netConfig = new WifiConfiguration(); if(!SSID.isEmpty() || !PASS.isEmpty())< netConfig.SSID=SSID; netConfig.preSharedKey = PASS; netConfig.hiddenSSID = false; netConfig.status = WifiConfiguration.Status.ENABLED; netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); >try < method.invoke(wifiManager, netConfig, enable); Log.e(TAG,"set hotspot enable method"); >catch (Exception ex) < >break; > > > 

Enabling the Hotspot the function call is: setWifiTetheringEnabled(true) and for disable setWifiTetheringEnabled(false) .

N.B. Be noted that SIM less devices are not supported to use Hotspot. You will not be able to create the Hotspot on those devices without root.

Hope this will be helpful for upcoming visitors.

Источник

Оцените статью
Adblock
detector