Android仅在手机被锁定或应用程序处于后台时激活BroadcastReceiver

时间:2014-06-16 14:45:10

标签: java android broadcastreceiver google-cloud-messaging

我有一个聊天应用程序,我希望我的GCM广播仅在手机屏幕被锁定或应用程序未激活时激活(主页按钮,而不是应用程序被杀!)

我尝试了以下内容:

boolean receiver_working = false;

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("com.flipflopdev.epvp_aj1987_chat");
    registerReceiver(new GcmBroadcastReceiver(), filter);
    Toast.makeText(getApplicationContext(), "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
    receiver_working = true;
   }

public void disableBroadcastReceiver(){
    ComponentName receiver = new ComponentName(getApplicationContext(), GcmBroadcastReceiver.class);
    PackageManager pm = getApplicationContext().getPackageManager();

    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
    Toast.makeText(getApplicationContext(), "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
    receiver_working = false;
   }

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

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

问题是即使活动刚刚开始,onResume()也会触发,这就是为什么我有布尔变量。当我现在通过主页按钮离开应用程序时,GCM通知会按照应有的方式启动(因为BR已激活),当我回到应用程序时,它表示BR已停用,但如果发送则通知仍会启动。

我的错误在哪里,有人可以帮助我吗?

0 个答案:

没有答案