我有一个应用程序,我想在我的应用程序运行时向通知栏显示我的应用程序图标,我还希望用户点击通知栏中的应用程序图标 我的应用程序将打开。这该怎么做?请帮助!
答案 0 :(得分:14)
要创建状态栏通知,请在onCreate方法中执行此操作:
获取对NotificationManager的引用:
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
实例化通知:
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
定义通知的扩展消息和意图:
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
将通知传递给NotificationManager:
private static final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
就是这样。您的用户现已收到通知。
答案 1 :(得分:7)
已接受的答案已弃用。以下是从Google documentation开始显示对话框的方法。
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable
.logo_listy).setContentTitle("My notification").setContentText("Hello World!");
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
答案 2 :(得分:3)
很少有建议:
答案 3 :(得分:0)
您需要发布包含意图启动应用的待处理意图的通知。 请参阅http://developer.android.com/guide/topics/ui/notifiers/notifications.html了解如何进行此操作,http://javablogs.com/Jump.action?id=628173了解您可能陷入的陷阱。