检测Android网络连接状态使用广播

4

我希望能够实现一个广播接收器,用于检测我的互联网连接。如果没有连接,则只需完成();它。但我仍然搞不清上下文,请检查下面的代码。

/**
 * This broadcast receiver is awoken after boot and registers the service that
 * checks for new photos from all the known contacts.
 */


public class ConnectionDetector extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {



    boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);

     if(noConnectivity){

         ((Activity)context).finish();
         //Show Warning Message
         //Close Application the way i suggested
     }

    }


}

AndroidManifest

 <receiver      android:name=".ConnectionDetector"
                        android:label="NetworkConnection">
        <intent-filter>
            <action     android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
        </receiver>

日志记录:

11-01 22:40:29.179: E/AndroidRuntime(29531): FATAL EXCEPTION: main
11-01 22:40:29.179: E/AndroidRuntime(29531): java.lang.RuntimeException: Unable to start receiver in.wptrafficanalyzer.actionbarsherlocknavtab.ConnectionDetector: java.lang.ClassCastException: android.app.ReceiverRestrictedContext
11-01 22:40:29.179: E/AndroidRuntime(29531):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:1809)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at android.app.ActivityThread.access$2400(ActivityThread.java:117)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at android.os.Looper.loop(Looper.java:130)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at android.app.ActivityThread.main(ActivityThread.java:3691)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at java.lang.reflect.Method.invokeNative(Native Method)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at java.lang.reflect.Method.invoke(Method.java:507)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at dalvik.system.NativeStart.main(Native Method)
11-01 22:40:29.179: E/AndroidRuntime(29531): Caused by: java.lang.ClassCastException: android.app.ReceiverRestrictedContext
11-01 22:40:29.179: E/AndroidRuntime(29531):    at in.wptrafficanalyzer.actionbarsherlocknavtab.ConnectionDetector.onReceive(ConnectionDetector.java:29)
11-01 22:40:29.179: E/AndroidRuntime(29531):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:1798)
11-01 22:40:29.179: E/AndroidRuntime(29531):    ... 10 more
1个回答

7

在BroadcastReceiver中获得的上下文不是一个Activity。BroadcastReceiver在Activity之外工作,除非您特别指定它与某个Activity绑定。

放弃通过在互联网问题发生时仅结束Activity而不通知用户的不良实践,您可以执行以下操作:

public abstract class ConnectionAwareActivity extends Activity {

protected final IntentFilter mIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); // A filter for a BR. We want to listen to internet changes
protected final ConnectionDetector mConnectionDetector = new ConnectionDetector(); // Creating an instance of our BR for activity to use

@Override
protected void onResume() {
    super.onResume();
    try {
        registerReceiver(mConnectionDetector, mIntentFilter); // Activity gets shown, we register a BR and it starts to receive notifications about internet changes
    } catch (Exception exc) {
        // whoops
    }
}

@Override
protected void onPause() {
    super.onPause();
    try {
        unregisterReceiver(mConnectionDetector); // Try to unregister BR, since when activity is not visible to user, we don't want to perform any operations on internet change
    } catch (Exception exc) {
        // whoops
    }
}

// Your BR that is encapsulated in Activity and therefore has access to it's methods, since it has access to Activity instance
protected class ConnectionDetector extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        if (noConnectivity) {
            finish();
        }

    }
}

将它用作其他活动的超类(本活动扩展自Activity,更改为任何内容),必须在连接错误时终止。

这是一种非常基本和有些错误的变体,因为您最好选择组合而不是超类。


谢谢Alex。您提供的代码对我来说太高级了。您有关于这个的教程或例子吗? - KC Chai
我们只需在活动中封装广播接收器。当向用户显示活动时,它会注册广播接收器,当暂停时则注销它。在你的示例中,BR已为整个应用程序注册,而在我的情况下,我们仅在活动期间注册它。 - Alex Orlov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接