In my application, I am using a Webview. So I want to monitor the network changes ie, offline or online cases. Based on this status I want to update/send some data to the javascript code in the background through the below code.
mWebview.evaluateJavascript(".object.setStatus(" + status +")",null);
I want to monitor these network changes if the app is in the background or closed and call the above code to set a value on the backend side.
I have written a BroadcastReceiver code to check the network changes. But how to run it always-on the background and how to call webview.evaluate() from there.
public class NetworkChangeReceiver extends BroadcastReceiver {
////"isOffline"
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onReceive(final Context context, final Intent intent) {
boolean mIsConnected = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (cm == null || capabilities == null) {
mIsConnected =false;
} else if ( capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
mIsConnected =true;
}
}
}
My app only support from Version 26 to 30.
Thanks In Advance!
question from:
https://stackoverflow.com/questions/65843996/android-monitor-the-network-changes-on-background-and-update-ui 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…