【问题标题】:How to show push notifications when screen is locked如何在屏幕锁定时显示推送通知
【发布时间】:2014-08-23 01:47:42
【问题描述】:

我有一个应用程序,它使用新的 gcm api 从自定义网络服务器接收推送通知。一切正常。但是,我也想在锁定屏幕上显示通知。

我四处搜索并找到了这篇文章,但没有帮助:Android how to show notification on screen

有没有什么简单的方法可以做到这一点?感谢您的帮助!

编辑 //

这是一些代码。

在 GCMHandler 中,我使用这个 sn-p 来显示通知:

   private void sendNotification() {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("message", message);
    intent.putExtra("pbid", pbid);
    intent.putExtra("alarm", alarm);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(alarm ? getString(R.string.txt_alarm_message_title) : getString(R.string.txt_info_message_title))
                    .setContentText(message);

    // play alarm tone
    if (alarm) playRingtone();

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

在应用程序的主要活动中,我使用了上面帖子中的代码:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    setContentView(R.layout.act_main);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON, WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED, WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
...
}

问题是,通知已显示,但在锁定屏幕上不可用。如果屏幕被锁屏,则不会收到推送通知;(

【问题讨论】:

  • 您尝试链接时出现什么问题。提供一些您尝试使用标志的代码
  • 我在原始帖子的编辑中发布了代码。
  • 谢谢。我试过了,但它仍然无法在 Android 4.4.2 上运行;-(您还有其他建议吗?
  • @Robin:你好,你找到这个问题的答案了吗?

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


【解决方案1】:

试试这个,它会起作用的。

int currentapiVersion = android.os.Build.VERSION.SDK_INT;

    if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        Notification noti = new Notification.Builder(
                getApplicationContext())
                .setContentTitle("New mail from " + " ")
                .setContentText(msg).setContentIntent(contentIntent)
                .setDefaults(1).setSmallIcon(R.drawable.gcm_cloud).build();
        PowerManager pm = (PowerManager) this
                .getSystemService(Context.POWER_SERVICE);

        WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        wl.acquire(15000);

        mNotificationManager.notify(NOTIFICATION_ID, noti);

    } 

【讨论】:

  • 这只会唤醒手机。 OP正在询问如何在屏幕锁定时显示通知。
  • 它的锁屏通知显示试试这个。然后发表评论。
  • 这个答案是错误的。问题是如何在锁定屏幕页面上显示通知,而不是在通知栏系统中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 2020-07-17
  • 1970-01-01
  • 2014-10-02
  • 2021-03-26
  • 1970-01-01
相关资源
最近更新 更多