在onResume()中销毁BroadcastReceiver

时间:2015-04-10 17:02:37

标签: android broadcastreceiver

我的MainActivity中有onResume()和onDestroy()方法。如何在onResume()方法中销毁registerReceiver。我试图将它分配给变量,但没有成功。



	@Override
	protected void onResume() {

		 registerReceiver(new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				check_wifi_available();

			}
		}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		unregisterReceiver();
		super.onDestroy();
	}




2 个答案:

答案 0 :(得分:3)

来自android文档:

  

如果在Activity.onResume()实现中注册接收者,   你应该在Activity.onPause()中取消注册它。 (你不会收到   意图暂停时,这将减少不必要的系统   开销)

将接收器定义为类变量,如下所示:

private BroadcastReceiver mReceiver = new BroadcastReceiver() { 
 @Override 
 public void onReceive(Context context, Intent intent) {
     check_wifi_available(); 
   } 
 } 

然后实现onPause()/ onResume()方法,如下所示:

@Override 
protected void onResume() { 
     super.onResume(); 
     registerReceiver(mReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    unregisterReceiver(mReceiver);
 }  

无需在onDestroy()方法中取消注册。

答案 1 :(得分:0)

在班级中定义接收器'属性:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
     @Override
    public void onReceive(Context context, Intent intent) {

    }
};

和这些方法:

@Override
public void onResume() {
    super.onResume();
    registerReceiver(broadcastReceiver, new IntentFilter("your package name"));
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(broadcastReceiver);
}