Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...