我不能停止接收广播

时间:2019-04-08 16:18:45

标签: android broadcastreceiver android-lifecycle

我不能停止接收广播。为什么?

这是我的代码:

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()时,该应用程序继续显示连接和断开充电的吐司消息。我不知道为什么。

1 个答案:

答案 0 :(得分:1)

我的猜测是(您在onPause()onStop()中使用的条件)br.isOrderedBroadcast()false,因此CustomReceiver不会被注销。

另外,根据文档,CustomReceiver / onCreate()onDestroy() / onResume()中的you should register/unregister onPause()