Use when you want to send request from WIFI if wifi has not data.
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void stayOnWifi(Context context) {
final ConnectivityManager connection_manager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
connection_manager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
ConnectivityManager.setProcessDefaultNetwork(network);
}
});
}
use this method when you want to send request from wifi if wifi does not have any data.
the issue of above code is when you forcefully set the data use priority.if we set wifi priority app will unable to use mobile data and if set priority for mobile data data then app will not able to use wifi no matter wifi has data or not.
Solution For Problem We should use Broadcast,Means when we want to send request from wifi which has no data use above method and after completing use the broadcast,it sets the available data which can be mobile or wifi. means restriction will remove.
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void stayOnMobileData(Context context) {
final ConnectivityManager connection_manager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
connection_manager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
ConnectivityManager.setProcessDefaultNetwork(network);
}
});
}
Broadcast
public class NetworkStateChangeBroadcast extends BroadcastReceiver {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceive(Context context, Intent intent) {
if (in.bets.bettywifi.ui.common.BaseActivity.checkNetworkStatus(context)) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()) {
BaseActivity.stayOnWifi(context);
} else if (mobile.isConnected()) {
BaseActivity.stayOnMobileData(context);
}
}
}
}