按下电源按钮后,GCM在一秒钟后没有收到消息(SLEEP)

时间:2014-08-04 04:33:25

标签: java android android-broadcastreceiver

请帮我解决这个问题吧.. 手机仅在设备开启时接收消息。 当按下电源按钮关闭(20-30)秒后,它会停止接收,并在接通时继续接收。 这是我的接收者。

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("GCM ", "GCM COME");
        ComponentName comp = new ComponentName(context.getPackageName(),
                MainService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

1 个答案:

答案 0 :(得分:0)

为Wakelock创建一个如下所示的类,

@SuppressLint("Wakelock")
public class WakeLocker {
private static PowerManager.WakeLock wakeLock;

@SuppressWarnings("deprecation")
public static void acquire(Context context) {
    if (wakeLock != null)
        wakeLock.release();

    PowerManager pm = (PowerManager) context
            .getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
            | PowerManager.ACQUIRE_CAUSES_WAKEUP
            | PowerManager.ON_AFTER_RELEASE, "WakeLock");
    wakeLock.acquire();
}

public static void release() {
    if (wakeLock != null)
        wakeLock.release();
    wakeLock = null;
}
}

并在BroadcastReceiver的onrecive方法中写下这一行

// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
// Releasing wake lock
WakeLocker.release();