I am trying to store a wifi network (and eventually cellular network) through ConnectivityManager for use later in my program to send data specifically through a local Wifi or cellular network simultaneously. I have followed this post (Make Android simultaneously use WiFi to talk to a device and mobile data to talk to a server? and How to stay connected through mobile network after WIFI is connected on Android?) to try and get it running. However the mWifiNetwork
is null. Using debug mode the variable mWifiNetwork
shows up as "108"
then when the '''onAvailable''' method is complete the variable turns back to null. Not sure why the variable is not storing the network correctly.
I created a class forceWifiNetwork that is called in onResume
forceWifiNetwork.java
public class forceWifiNetwork {
//setting up a context variable and method to use "getSystemService"
// this way we do not need to extend MainActivity class to this class
// But when we initialize this class in main activity we will have to pass in "this" to the class as a parameter
Context mContext;
private ConnectivityManager.NetworkCallback mWifiNetworkCallback;
public Network mWifiNetwork;
final ConnectivityManager manager;
public forceWifiNetwork(Context mContext){
this.mContext = mContext;
manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
}
public void cellConnect(){
if (mWifiNetworkCallback == null){
// Init only once
mWifiNetworkCallback = new ConnectivityManager.NetworkCallback(){
@Override
public void onAvailable(final Network network){
try{
//Save this network for later use
mWifiNetwork = network;
}catch(Exception e){
Log.i("onAvailable ERROR","Error in onAvailable method");
}
}
};
}
NetworkRequest.Builder wifiBuilder;
wifiBuilder = new NetworkRequest.Builder();
//set the transport type to do wifi
wifiBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
//wifiBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
manager.requestNetwork(wifiBuilder.build(),mWifiNetworkCallback);
}
}
onResume (in MainActivity.java)
@Override
public void onResume(){
super.onResume();
try {
forceWifiNetwork myWifiNetwork = new forceWifiNetwork(this);
myWifiNetwork.cellConnect();
if (myWifiNetwork.mWifiNetwork == null) {
Log.i("onResume", "mWifiNetwork is null");
} else {
Log.i("onResume", "mWifiNetwork is not null");
}
}catch(Exception e){
Log.i("ERROR IN ONRESUME","error");
e.printStackTrace();
}
}
I also currently have these permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />