我正在尝试监听网络连接的变化。当我打开或关闭飞行模式时,我的广播接收器似乎没有启动。我不确定这是否是因为我没有正确注册它,或者飞行模式更改可能不会导致它触发。任何建议表示赞赏。谢谢!
我的清单:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<receiver android:name=".NetworkReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
我的广播接收器类:
public class NetworkReceiver extends BroadcastReceiver {
private SharedPreferences prefs;
private SharedPreferences.Editor prefEditor;
@Override
public void onReceive(Context context, Intent intent) {
prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefEditor = prefs.edit();
Boolean has_connection = prefs.getBoolean("has_connection", false);
prefEditor.putBoolean("has_connection", !has_connection);
prefEditor.commit();
System.err.println("Network Receiver notified of a connectivity change!");
System.err.println("New has_connection: " + !has_connection);
}
}
此外,在应用程序运行大约 45 秒后,它突然崩溃并出现以下错误:
09-06 21:29:48.775: E/AndroidRuntime(15613): java.lang.RuntimeException: Unable to instantiate receiver com.mysite.myapp.NetworkReceiver: java.lang.ClassNotFoundException: com.mysite.myapp.NetworkReceiver