我在从GCM Server收到通知消息时遇到问题。设备在没有空闲或处于运行状态时会正常收到通知但是当设备空闲10-15分钟时设备无法获得通知而且全部已注册的设备未从GCM服务器获取通知。如何解决此问题?
答案 0 :(得分:1)
通常情况下,您的应用需要在睡眠时唤醒。
将此信息放入清单文件中,以便在收到邮件时唤醒您的设备
<uses-permission android:name="android.permission.WAKE_LOCK" />
添加java类名称WakeLocker.java
public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
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;
}
}
调用可能在您的MainActivity.java中的'private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver()'中的上述代码
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
// Showing received message
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
希望这会有所帮助