Android 7.1 couldn't enable wifi hotspot programmatically - android

I am trying that opening Wifi hotspot in android,When I run below code it runs successfully for Api 28 I can open Wifi hotspot without getting errror but When I run it in Api 25 for Android 7.1 device it gets below errors, it says get WRITE_SETTINGS permission,but When I tested for Api 28 it doesn't necessary for running application,Why can I get this errros and How can I run it for android Api 25
Getting Errors
W/System.err: java.lang.NoSuchMethodException: setWifiApEnabled [class android.net.wifi.WifiConfiguration, boolean]
at java.lang.Class.getMethod(Class.java:1981)
at java.lang.Class.getMethod(Class.java:1637)
at com.kocsistem.pixageoneandroid.utils.Utils.configApState(Utils.java:1126)
at com.kocsistem.pixageoneandroid.utils.Utils.openHotspot(Utils.java:1095)
at com.kocsistem.pixageoneandroid.network.broadcast.NetworkChangeReceiver$2.run(NetworkChangeReceiver.java:120)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Open Hotspot code
public static void openHotspot(Context context,boolean enable){
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
assert manager != null;
try {
manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
#SuppressLint("SetTextI18n")
#Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
Log.i("Wifi Hotspot is on now , reservation is : %s", reservation.toString());
mReservation = reservation;
WifiManager.LocalOnlyHotspotReservation mReservation = reservation;
String key = mReservation.getWifiConfiguration().preSharedKey;
Log.i("key:",key);
String ussid = mReservation.getWifiConfiguration().SSID;
Log.i("ussid:",ussid);
}
#Override
public void onStopped() {
super.onStopped();
Log.i("onStopped: ","");
}
#Override
public void onFailed(int reason) {
super.onFailed(reason);
Log.i("onFailed: ","");
}
}, new Handler());
}catch (Exception e){
e.printStackTrace();
}
}else{
//for Api<26
configApState(context);
}
}
check whether wifi hotspot on or off
public static boolean isApOn(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
try {
Method method = wifimanager.getClass().getDeclaredMethod("isWifiAp Enabled");
method.setAccessible(true);
return (Boolean) method.invoke(wifimanager);
}
catch (Throwable ignored) {}
return false;
}
toggle wifi hotspot on or off
public static boolean configApState(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
WifiConfiguration wificonfiguration = null;
try {
// if WiFi is on, turn it off
if(isApOn(context)) {
wifimanager.setWifiEnabled(false);
}
Method method = wifimanager.getClass().getMethod("setWifiApEnabled ", WifiConfiguration.class, boolean.class);
method.invoke(wifimanager, wificonfiguration, !isApOn(context));
return true;
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}

this code works for Android Api 26 (Oreo) and above , its not gonna work with nougat (api 25)
there is another way to do that , you have to get method called "setWifiApEnabled" Check this peace of code
PS: you have to convert the code from c# to java and dont forget to grant the write settings permission ...
private bool ActivateTethering(string ssid, string password)
{
var myConfiguration = new WifiConfiguration();
WifiManager wifimanager = (WifiManager)Context.GetSystemService(Context.WifiService);
myConfiguration.Ssid = ssid;
myConfiguration.PreSharedKey = password;
myConfiguration.AllowedAuthAlgorithms.Set((int)AuthAlgorithmType.Shared);
myConfiguration.AllowedProtocols.Set((int)ProtocolType.Rsn);
myConfiguration.AllowedProtocols.Set((int)ProtocolType.Wpa);
myConfiguration.AllowedKeyManagement.Set((int)KeyManagementType.WpaPsk);
var enableWifi = wifimanager.Class.GetDeclaredMethods();
try
{
bool setWifiConfig = false;
foreach (var method in enableWifi)
{
if (method.Name.Equals("setWifiApEnabled"))
{
setWifiConfig = (bool)method.Invoke(wifimanager, myConfiguration, true);
break;
}
}
}
catch (InvocationTargetException e)
{
Console.WriteLine(e.Data.ToString());
}
return setWifiConfig ;
}

Related

How can I connect Android to Arduino MKR1000 over TCP/IP protocol?

I am developing an Android app to control an Arduino MKR1000 board, by communicating over the TCP/IP networking protocol. The Arduino works as an Access Point and send data, when there is a client available. My Android app manage to connect to Arduino's WiFi shield, but I have an issue with implementing the TCP client, on Android side. In fact, when I try to connect the Socket on the specified port number, on the named host, I get a Socket Exception.
I have already seen some answers:
java.net.SocketException: Software caused connection abort: recv failed, with java.net.SocketException: Connection reset
Official reasons for "Software caused connection abort: socket write error"
java.net.SocketException: Software caused connection abort: connect
But I haven't been able to figure out how to solve this.
Socket Exception:
W/System.err: java.net.SocketException: Software caused connection abort
W/System.err: at java.net.PlainSocketImpl.socketConnect(Native Method)
W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
W/System.err: at java.net.Socket.connect(Socket.java:586)
W/System.err: at java.net.Socket.connect(Socket.java:535)
W/System.err: at java.net.Socket.<init>(Socket.java:427)
W/System.err: at java.net.Socket.<init>(Socket.java:243)
W/System.err: at com.progetto.xxxxx.arduino.MyIntentService.onHandleIntent(MyIntentService.java:69)
W/System.err: at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:67)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.os.HandlerThread.run(HandlerThread.java:61)
Android code:
TCP client
public class MyIntentService extends IntentService {
Socket mSocket = null;
public static final int PORT = 2390;
InetAddress local = null;
public MyIntentService() {
super("MyIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
try {
local = InetAddress.getByName("192.168.1.7");
mSocket=new Socket(local,PORT); // Exception occurs
Log.i(TAG, "socket");
} catch (UnknownHostException e) {
Log.i(TAG, "UNknownHost");
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "IOEXCeption");
}
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION))
{
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo!=null)
{
String ssidN = wifiInfo.getSSID();
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean connected = info.isConnected();
if (connected)
{
if (ssidN.contains(ssid))
{
startService(intents);
}
}
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.disconnect();
wifiManager.setWifiEnabled(true);
intents=new Intent(this,MyIntentService.class);
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
}
public void WifiAp(){
LayoutInflater layoutInflater=getLayoutInflater();
view_pass=layoutInflater.inflate(R.layout.wifi_item,null);
Log.i(TAG, "view");
txt_annulla=(TextView)view_pass.findViewById(R.id.txt_annulla);
txt_connetti=(TextView)view_pass.findViewById(R.id.txt_connetti);
final android.app.AlertDialog.Builder alertDialog=new android.app.AlertDialog.Builder(this);
alertDialog.setView(view_pass);
final android.app.AlertDialog dialog = alertDialog.create();
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
window.setGravity(Gravity.CENTER);
dialog.show();
txt_annulla.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
txt_connetti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
wifiManager.disconnect();
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\"";
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
int newNetworkId = wifiManager.addNetwork(conf);
//Adds to the list of network and returns the network id which can be used to enable it later.
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.power:
WifiAp();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Arduino code:
#include <SPI.h>
#include <WiFi101.h>
#include <Arduino.h>
char apssid[] = "WifiMkr";
IPAddress ipC(192, 168, 1, 7);
int status = WL_IDLE_STATUS;
unsigned int localport = 2390;
//IPAddress remoteIp;
unsigned long timeM=0;
WiFiServer server(localport);
WiFiClient client;
IPAddress ip;
unsigned long tsample=1;
void setup() {
Serial.begin(9600);
while (!Serial) {
// wait for serial port to connect. Needed for native USB port only
}
Serial.println("Access Point");
if (WiFi.status() == WL_NO_SHIELD)
{
Serial.println("WiFi shield non รจ presente");
}
WiFi.config(ipC);
Serial.println("Creating access point named: ");
Serial.println(apssid);
if (WiFi.beginAP(apssid) != WL_AP_LISTENING) {
Serial.println("Creating access point failed");
}else{
Serial.println("Creating access point success");
}
delay(1000);
server.begin();
printWiFiStatus();
// compare the previous status to the current status
Serial.println("\nStarting connection to server...");
}
void loop() {
unsigned long time=millis();
if (status != WiFi.status()) {
//it has changed update the variable
status = WiFi.status();
if (status == WL_AP_CONNECTED)
{
byte remoteMac[6];
// a device has connected to the AP
Serial.print("Device connected to AP, MAC address: ");
WiFi.APClientMacAddress(remoteMac);
Serial.print(remoteMac[5], HEX);
Serial.print(":");
Serial.print(remoteMac[4], HEX);
Serial.print(":");
Serial.print(remoteMac[3], HEX);
Serial.print(":");
Serial.print(remoteMac[2], HEX);
Serial.print(":");
Serial.print(remoteMac[1], HEX);
Serial.print(":");
Serial.println(remoteMac[0], HEX);
}
else
{
// a device has disconnected from the AP, and we are back in listening mode
Serial.println("Device disconnected from AP");
}
}
client= server.available();
if(client){
Serial.println("hello client");
while(client.connected()){
//
int value = analogRead(A3);
client.write(value);
Serial.println("millis");
Serial.println(tsample);
Serial.println(millis());
Serial.println(timeM);
while(millis()<timeM+tsample);
}
}
}
void printWiFiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}

hotspot set number of users programmatically

i've used a method to create a hotspot and it's working
but i need to set a specific number of maximum connections that will be in this hotspot
thanks in advance
My current code :
private boolean configHotspot(String name,String pass) {
WifiConfiguration wifiCon = new WifiConfiguration();
wifiCon.SSID = name;
wifiCon.preSharedKey = pass;
wifiCon.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiCon.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
try
{
Method setWifiApMethod = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
boolean apstatus=(Boolean) setWifiApMethod.invoke(wifimanager, wifiCon,true);
return apstatus;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}

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

I know how to turn on/off wifi hot spot using reflection in android using below method.
private static boolean changeWifiHotspotState(Context context,boolean enable) {
try {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Method method = manager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class,
Boolean.TYPE);
method.setAccessible(true);
WifiConfiguration configuration = enable ? getWifiApConfiguration(manager) : null;
boolean isSuccess = (Boolean) method.invoke(manager, configuration, enable);
return isSuccess;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
But the above method is not working 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 there any other way to on/off hotspot on android 8.0
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:
MyOreoWifiManager and;
CallbackMaker
I lost patience trying to get my DexMaker-generated callback to fire the MyOnStartTetheringCallback so all that code is in disarray and commented out.
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
As per Jon suggestion, I got another way to enable WifiHotSpot in Android Oreo and above.
public boolean enableTetheringNew(MyTetheringCallback callback) {
File outputDir = mContext.getCodeCacheDir();
try {
proxy = ProxyBuilder.forClass(classOnStartTetheringCallback())
.dexCache(outputDir).handler(new InvocationHandler() {
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
switch (method.getName()) {
case "onTetheringStarted":
callback.onTetheringStarted();
break;
case "onTetheringFailed":
callback.onTetheringFailed();
break;
default:
ProxyBuilder.callSuper(proxy, method, args);
}
return null;
}
}).build();
} catch (IOException e) {
e.printStackTrace();
}
ConnectivityManager manager = (ConnectivityManager) mContext.getApplicationContext().getSystemService(ConnectivityManager.class);
Method method = null;
try {
method = manager.getClass().getDeclaredMethod("startTethering", int.class, boolean.class, classOnStartTetheringCallback(), Handler.class);
if (method == null) {
Log.e(TAG, "startTetheringMethod is null");
} else {
method.invoke(manager, TETHERING_WIFI, false, proxy, null);
}
return true;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return false;
}
private Class classOnStartTetheringCallback() {
try {
return Class.forName("android.net.ConnectivityManager$OnStartTetheringCallback");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}

How to get notification when a device connects to your android wifi tethering AP?

I enable wi-fi tethering through my application in my android device. How do I get notification in my application when someone connects to the Wi-Fi network tethered by my application? Do I need to register for some specific broadcast receivers?
I have pasted below the application source code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((ToggleButton) findViewById(R.id.toggle_tethering)).setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
Boolean result = false;
WifiConfiguration config = new WifiConfiguration();
config.SSID = "Tab3OpenWifi";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
String setWifiApConfigurationMethodName = "setWifiApConfiguration";
Method setWifiApConfigurationMethod = wifiManager.getClass().getMethod(setWifiApConfigurationMethodName, WifiConfiguration.class);
result = (Boolean) setWifiApConfigurationMethod.invoke(wifiManager, config);
if (result) {
String setWifiApEnableMethodName = "setWifiApEnabled";
Method setWifiApEnableMethod = wifiManager.getClass().getMethod(setWifiApEnableMethodName, WifiConfiguration.class, boolean.class);
String message;
if (isChecked) {
result = (Boolean) setWifiApEnableMethod.invoke(wifiManager, null, true);
if (result) {
message = "Enabling tethering successfully";
} else {
message = "Enabling tethering failed";
}
} else {
result = (Boolean) setWifiApEnableMethod.invoke(wifiManager, null, false);
if (result) {
message = "Disabling tethering successfully";
} else {
message = "Disabling tethering failed";
}
}
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to update Wifi Tethering config.", Toast.LENGTH_SHORT).show();
}
}
I used below broadcast receiver to get the AP state.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"mReceiver.onReceive>>");
String action = intent.getAction();
if (WIFI_AP_STATE_CHANGED_ACTION.equals(action)) {
Log.d(TAG,"WIFI_AP_STATE_CHANGED_ACTION");
} else if (ACTION_TETHER_STATE_CHANGED.equals(action)) {
ArrayList<String> available = intent.getStringArrayListExtra(
EXTRA_AVAILABLE_TETHER);
ArrayList<String> active = intent.getStringArrayListExtra(
EXTRA_ACTIVE_TETHER);
ArrayList<String> errored = intent.getStringArrayListExtra(
EXTRA_ERRORED_TETHER);
Log.d(TAG,"==Available==");
for(String str : available)
Log.d(TAG, ""+str);
Log.d(TAG,"==Active==");
for(String str : active)
Log.d(TAG, ""+active);
Log.d(TAG,"==Error==");
for(String str : errored)
Log.d(TAG, ""+str);
} else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
}
Log.d(TAG,"mReceiver.onReceive<<");
}
};
I don't think there is an API for that, nor any broadcast event which you can listen to.
The only option that I can think of is operating at a lower level, i.e. the kernel level. I am no expert, but I used to monitor the /proc/net/tcp file to look for open connections. That may be a starting point for you.
I also wrote a simple library, if you want to get a glimpse of how I did it. You can find it here: https://github.com/dextorer/AndroidTCPSourceApp

How to create access point programmatically

I've written the code to create an access point for android devices. I've tested on both emulator and real device.But it doesn't work. Where did i get wrong?
public class MainWAP extends Activity {
WifiManager wifiManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wap);
}
public void openWifi(View v) {
createWifiAccessPoint();
}
private void createWifiAccessPoint() {
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.SSID = "AccessPoint";
netConfig.allowedAuthAlgorithms.set(
WifiConfiguration.AuthAlgorithm.OPEN);
try {
boolean apstatus = (Boolean) method.invoke(
wifiManager, netConfig, true);
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);
}
}
}
}
if (apstatus) {
Log.d("Splash Activity",
"Access Point created");
} else {
Log.d("Splash Activity",
"Access Point creation failed");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
if (!methodFound) {
Log.d("Splash Activity",
"cannot configure an access point");
}
}
}
Your WiFiManager is definately not initialized.
In your onCreate method add this:
wifiManager = (WiFiManager) getSystemService(Context.WIFI_SERVICE);
You need few things to make this code to work.
1) Init wifiManager onCreate() :
WifiManager wifiManager = (WiFiManager) getSystemService(Context.WIFI_SERVICE);
2) You need to ask for this permissions in you AndroidManifest.xml :
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />
3) Your application need to be signed with system certificates.
With your method of exploiting undocumented APIs using reflection, things might not work well in all scenarios.
Well, you can try adding these in your manifest file and give a try.
android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.WRITE_APN_SETTINGS

Categories

Resources