gpt4 book ai didi

Android GCM 不向设备发送通知消息

转载 作者:行者123 更新时间:2023-11-30 03:18:39 27 4
gpt4 key购买 nike

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

最佳答案

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

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

    <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

    希望对您有所帮助

关于Android GCM 不向设备发送通知消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566706/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com