【问题标题】:Android GCM not send notification message to deviceAndroid GCM 不向设备发送通知消息
【发布时间】:2013-10-24 13:02:04
【问题描述】:

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

【问题讨论】:

    标签: android push-notification google-cloud-messaging


    【解决方案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();
      }
      };
      

      感谢This source

      希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      相关资源
      最近更新 更多