1

我在从 GCM 服务器获取通知消息时遇到问题。设备在不空闲或处于运行状态时会正确收到通知,但是当设备空闲 10-15 分钟时,设备无法收到通知,所有注册的设备都是没有收到来自 GCM 服务器的通知。如何解决这个问题?

4

1 回答 1

1

通常,您的应用需要在睡眠时唤醒。

  1. 将其放入清单文件以在收到消息时唤醒您的设备

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    
  2. 添加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;
        }
    }
    
  3. 在可能位于 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();
    }
    };
    

    感谢这个来源

    希望这可以帮助

于 2013-10-24T13:22:40.633 回答