Android Broadcastreceiver仅在待机或应用程序处于非活动状态

时间:2014-06-26 11:00:24

标签: java android broadcastreceiver

如果应用程序进入后台或方便处于待机状态(已锁定),我希望我的应用中的Broadcastreceiver才能启动。因此,我通过onPause() onDestroy()onResume()进行了尝试,但有时它会激活/停用,因为这些方法是不规则的。有没有更好的解决方案来实现我的目标?

我的代码:

public void enableBroadcastReceiver(){
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.google.android.c2dm.intent.RECEIVE");
    filter.addAction("com.google.android.c2dm.intent.REGISTRATION");
    filter.addCategory("xxx");
    receiver = new GcmBroadcastReceiver();
    registerReceiver(receiver, filter);
    Toast.makeText(getApplicationContext(), "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
    receiver_working = true;
   }

public void disableBroadcastReceiver(){
    try {
        unregisterReceiver(receiver);
        Toast.makeText(getApplicationContext(), "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
        receiver_working = false;
    } catch (IllegalArgumentException e) {
    }
   }

@Override
public void onResume() {
    super.onResume();
    if(receiver_working) {
        disableBroadcastReceiver();
    }
}

@Override
public void onPause() {
    super.onPause();
    if(!receiver_working) {
        enableBroadcastReceiver();
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    if(receiver_working) {
        disableBroadcastReceiver();
    }
}

1 个答案:

答案 0 :(得分:1)

也许不是在设备处于睡眠模式时禁用接收器,而是可以在接收器内检查这种情况。

在Receiver内部,您只需输入一个if,检查是否有活动应用程序(例如,您可以通过调用isScreenOn方法检查屏幕是否已关闭)。

我希望这是你正在寻找的东西;)