Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

broadcastreceiver - Android Monitor the network changes on background and update UI

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...