我不能停止接收广播。为什么?
这是我的代码:
public class MainActivity extends AppCompatActivity {
BroadcastReceiver br = new CustomReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver br = new CustomReceiver();
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
this.registerReceiver(br, filter);
}
@Override
protected void onStart() {
super.onStart();
if(!br.isOrderedBroadcast())
this.registerReceiver(br, filter);
}
@Override
protected void onStop() {
super.onStop();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
@Override
protected void onPause() {
super.onPause();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
@Override
protected void onResume() {
super.onResume();
if(!br.isOrderedBroadcast())
this.registerReceiver(br, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
}
public class CustomReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
String toastMessage = "TOAST";
switch (intentAction){
case Intent.ACTION_POWER_CONNECTED:
toastMessage="Power Connected!";
break;
case Intent.ACTION_POWER_DISCONNECTED:
toastMessage="Power Disconnected!";
break;
}
Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
}
}
当我转到onPause()
和onStop()
时,该应用程序继续显示连接和断开充电的吐司消息。我不知道为什么。
答案 0 :(得分:1)
我的猜测是(您在onPause()
和onStop()
中使用的条件)br.isOrderedBroadcast()
为false
,因此CustomReceiver
不会被注销。
另外,根据文档,CustomReceiver
/ onCreate()
或onDestroy()
/ onResume()
中的you should register/unregister onPause()
。