简体   繁体   中英

How to detect Internet Connection State via CONNECTIVITY_CHANGE broadcast

I need to handle the connectivity change broadcast in my app. Every thing is great except that when it comes for the broadcast the application crashes. I am using the following code in my Broadcast :


@Override
public void onReceive(Context context, Intent intent) {
    Log.i("NET", "Broadcast started");
    Intent startServiceIntent = new Intent(context, NewsService.class);

    boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    if(noConnectivity) {
        context.stopService(startServiceIntent);
        Toast.makeText(context, "Connection is terminated!", Toast.LENGTH_LONG).show();
        Log.i("NET", "Stopped");
    }
    else {
        context.startService(startServiceIntent);
        Toast.makeText(context, "Connection is ok!", Toast.LENGTH_LONG).show();
    }
}

This code is supposed to stop a service when no internet connection is found and to start it whenever it finds a connection.

最后,经过2天的搜索,我发现了问题所在,这与广播所放置的包裹有关, 我在这里找到了

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM