正如标题所说,我无法从 NetWorkInfo 类中获取 Broadcastreceiver 中的状态。
它在日志输出中返回一些错误,如下所示。
我需要你的帮助。
这是日志输出和 Broacastreceiver 类,我还注意到我已经添加了所有权限(Access Network State et Internet)和广播意图 action android:name="android.net.conn.CONNECTIVITY_CHANGE
。
所以我敢说 manifest.xml 文件没有问题。
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
State state = activeNetwork.getState();
switch (state) {
case CONNECTING:
Toast.makeText(context, "connecting", Toast.LENGTH_SHORT).show();
break;
日志输出为:
java.lang.RuntimeException: Unable to start receiver com.example.test.ConnectivityChangeReceiver: java.lang.NullPointerException
E/AndroidRuntime( 9873): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2668)
E/AndroidRuntime( 9873): at android.app.ActivityThread.access$1800(ActivityThread.java:172)
E/AndroidRuntime( 9873): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
E/AndroidRuntime( 9873): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime( 9873): at android.os.Looper.loop(Looper.java:146)
E/AndroidRuntime( 9873): at android.app.ActivityThread.main(ActivityThread.java:5653)
E/AndroidRuntime( 9873): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 9873): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime( 9873): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
E/AndroidRuntime( 9873): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
E/AndroidRuntime( 9873): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 9873): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 9873): at com.example.test.ConnectivityChangeReceiver.onReceive(ConnectivityChangeReceiver.java:27)
E/AndroidRuntime( 9873): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2653)