简体   繁体   English

如何通过CONNECTIVITY_CHANGE广播检测Internet连接状态

[英]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天的搜索,我发现了问题所在,这与广播所放置的包裹有关, 我在这里找到了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 一旦收到广播意图CONNECTIVITY_CHANGE,如何更新小部件 - How to update widget once broadcast intent CONNECTIVITY_CHANGE is received CONNECTIVITY_CHANGE广播Android O. - CONNECTIVITY_CHANGE Broadcast Android O BroadCast CONNECTIVITY_CHANGE被多次触发 - BroadCast CONNECTIVITY_CHANGE Triggered Many Times CONNECTIVITY_CHANGE的问题 - issue with CONNECTIVITY_CHANGE 如何用CONNECTIVITY_CHANGE定义Broadcastreceiver? - how define Broadcastreceiver with CONNECTIVITY_CHANGE? 互联网连接更改广播不会发生 - Internet Connectivity Change Broadcast Not Happening 如何使用FirebaseJobDispatcher可靠地替换CONNECTIVITY_CHANGE - How to use FirebaseJobDispatcher to replace CONNECTIVITY_CHANGE reliably 启用WiFi时,广播接收器能否接收移动数据CONNECTIVITY_CHANGE通知? - Can a Broadcast Receiver receive a Mobile Data CONNECTIVITY_CHANGE notification while WiFi is enabled? 启用/禁用接收器(CONNECTIVITY_CHANGE)会导致APPWIDGET_UPDATE广播 - Enabling/disableing receiver (CONNECTIVITY_CHANGE) causes APPWIDGET_UPDATE broadcast 如何使用广播接收器检查互联网连接并更改意图 - How to check internet connectivity using broadcast receiver and Change the intent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM