Android如何在屏幕上显示通知?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (11)

我一直在处理推送通知,并且能够实现它并将其显示在状态栏上,但我面对的问题是,即使手机处于锁定状态,我也想要显示它,在锁定屏幕上显示,我看到类似的通知,但无法找到任何示例。

例如: 就像你收到未接电话时一样,它会在屏幕上的锁定按钮下显示:

String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon_launcher;
CharSequence tickerText = "MyApplication";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE|Notification.DEFAULT_LIGHTS;;
CharSequence contentTitle = this.title;
CharSequence contentText = this.message;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTICE_ID, notification);
提问于
用户回答回答于

你有没有尝试用标志创建alertdialog?该flag_show_when_locked应该可以的你试试吧。

用户回答回答于

使用NotificationCompat.Builder创建通知 :

NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher) // notification icon
            .setContentTitle("Notification!") // title for notification
            .setContentText("Hello word") // message for notification
            .setAutoCancel(true); // clear notification after click
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);
NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());

扫码关注云+社区