0

我有 BroadcastReceiver (NetworkListener)。

public class NetworkReceiver extends BroadcastReceiver {
Context context;
public static NetworkReceiver instance = new NetworkReceiver();
public static InnerObservable observable = instance. new InnerObservable();
...

此接收器发送通知:

@Override
public void onReceive(Context ctx, Intent intent) {

    Log.d("tag", "onReceive");

    NotificationManager notif = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(android.R.drawable.ic_dialog_alert,"bla-bla-bla",System.currentTimeMillis());

清单文件:

 <receiver 
        android:name="com.mypckg.network.NetworkReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver> 

它工作正常。但手机重启后,它继续工作。如何避免?

4

2 回答 2

1

如果您希望广播接收器在应用程序启动时开始工作,那么您应该以编程方式从您的主要活动中注册/取消注册它:

private BroadcastReceiver networkReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    networkReceiver = new NetworkReceiver();
    registerReceiver(networkReceiver, ConnectivityManager.CONNECTIVITY_ACTION);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(networkReceiver)
}
于 2012-11-09T09:42:31.453 回答
1

您可以使用 PackageManager 来禁用在您的清单中注册的 BroadcastReceiver,检查此线程以获取代码。

另一种解决方案是动态注册此接收器,可能在服务中。只要服务处于活动状态,接收器就会处于活动状态并已注册,因此您可以通过启动/停止服务轻松切换接收器。这可能不适合您的用例,但是您没有提供太多详细信息。

于 2012-11-09T09:44:43.367 回答