【问题标题】:Android: How to turn on screen when new notification received?Android:收到新通知时如何打开屏幕?
【发布时间】:2017-06-07 18:26:12
【问题描述】:

我几乎尝试了所有方法,但我不明白在后台模式下收到新通知时如何打开手机屏幕。

我正在使用 FCM。当应用程序在后台时,收到的通知由系统托盘管理。收到新东西时如何要求系统托盘打开屏幕?谢谢!

【问题讨论】:

    标签: android firebase push-notification firebase-cloud-messaging android-notifications


    【解决方案1】:

    答案终于来了。

    如果您使用 Firebase API 从服务器向设备发送通知,请记住 扩展 FirebaseMessagingService 中的 onMessageReceived() 方法仅调用如果您发送这样的通知,则在后台:

                            $msg = array
                            (
                                'body'  => $newsObj['description'],
                            );
                            $fields = array
                            (
                                'registration_ids'  => $registrationIds,
                                'data'          => $msg,
                                'priority'  => "high"
                            );
    

    你看,如果你把“data”属性改为“notification”,onMessageReceived()方法只会在应用位于FOREGROUND。

    要在收到新通知时打开屏幕,请将以下代码放入您的 onMessageReceived() 方法中:

            // Turn on the screen for notification
            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            boolean result= Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT_WATCH&&powerManager.isInteractive()|| Build.VERSION.SDK_INT< Build.VERSION_CODES.KITKAT_WATCH&&powerManager.isScreenOn();
    
            if (!result){
                PowerManager.WakeLock wl = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MH24_SCREENLOCK");
                wl.acquire(10000);
                PowerManager.WakeLock wl_cpu = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MH24_SCREENLOCK");
                wl_cpu.acquire(10000);
            }
    

    在 AndroidManifest.xml 中:

        <uses-permission android:name="android.permission.WAKE_LOCK" />
    

    就是这样!

    【讨论】:

    • PowerManager.FULL_WAKE_LOCK 已弃用,没有它怎么办?
    【解决方案2】:

    试试这个

    你要做一件事,当你显示通知时,你必须广播这个意图。在FirebaseMessagingService扩展类的onMessageReceived(RemoteMessage remoteMessage)方法中生成通知后

    Intent in=new Intent(Intent.ACTION_POWER_CONNECTED);
            getActivity().sendBroadcast(in);
    

    【讨论】:

    • 我正在使用 php 从我的服务器发送通知。因此通知不会在设备上本地处理。在这种情况下我应该把这段代码放在哪里?
    • 你在哪里定义通知正文?
    • 在服务器上的 php 中。我正在通过 firebase api 发送通知。
    • 从哪里调用这个 notificationManager.notify();声明?
    • 我没有在设备上调用它。在我的服务器运行脚本后,通知会自动出现在屏幕上。唯一的问题是屏幕没有打开,我不知道该怎么做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多