Android Notification的使用

        Android 4.1 (Jelly Bean) 增强了通知功能,在AndroidManifest.xml中可以为Activity添加属性android:parentActivityName="MainActivity",实现点击通知打开ResultActivity时,再按返回键,回到MainActivity,而不是回到之前的Task。只在4.1的机器上有效,在2.x的机器上和以前没有任何区别。

        核心代码如下:

    public void showNotification() {
    	NotificationCompat.Builder mBuilder =
    			  new NotificationCompat.Builder(this)
    			  .setSmallIcon(R.drawable.ic_launcher)
    			  .setContentTitle("My Notification")
    			  .setContentText("Hello World");
    	
    	//NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
//    	String [] events = new String[6];
//    	inboxStyle.setBigContentTitle("Event tracker details:");
//    	for (String event : events) {
//    		inboxStyle.addLine(event);
//    	}
//    	mBuilder.setStyle(inboxStyle);
    	
    	Intent intent = new Intent(this, ResultActivity.class);
    	
    	//The stack builder object will contain an artificial back stack for the started Activity.
    	//This ensures that navigating backward from the Activity leads out of your application to the Home screen
    	TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    	
    	//Adds the back stack for the Intent (but not the Intent itself)
    	stackBuilder.addParentStack(ResultActivity.class);
    	
    	//Adds the intent that starts the Activity to the top of the stack
    	stackBuilder.addNextIntent(intent);
    	
    	PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    	mBuilder.setContentIntent(pendingIntent);
    	
    	mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    	mBuilder.setAutoCancel(true);
    	//mBuilder.setDefaults(Notification.DEFAULT_ALL);
    	
    	NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    	mgr.notify(0, mBuilder.build());
    }


        部分AndroidManifiest.xml代码
<activity android:name=".ResultActivity"
            android:parentActivityName=".MainActivity" >
</activity>


参考:http://developer.android.com/guide/topics/ui/notifiers/notifications.html

你可能感兴趣的:(android,notification)