Android Notification详解

Notification,俗称通知,是一种具有全局效果的通知,它展示在屏幕的顶端,首先会表现为一个图标的形式,当用户向下滑动的时候,展示出通知具体的内容。

关于Notification的详细介绍可参考Android Developer Notifications


Notification视觉风格
Notification有两种视觉风格,一种是标准视图(Normal view)、一种是大视图(Big view)。标准视图在Android中各版本是通用的,但是对于大视图而言,仅支持Android4.1+的版本。
标准视图
标准视图显示的大小要保持在64dp高,宽度为屏幕标准。标准视图的通知主体内容有一下几个:


  1. 通知标题。
  2. 大图标。
  3. 通知内容。
  4. 通知消息。
  5. 小图标。
  6. 通知的时间,一般为系统时间,也可以使用setWhen()设置。
大视图
大视图(Big View)而言,它的细节区域只能显示256dp高度的内容,并且只对Android4.1+之后的设备才支持,它比标准视图不一样的地方,均需要使用setStyle()方法设定,它大致的效果如下:



大视图和标准视图几乎一样,唯一的不同在7 细节部分。每个大视图可将此部分设置成不同样式。可供选择的样式如下:
Big picture style
在细节部分显示一个256dp高度的位图。
Big text style
在细节部分显示一个大的文本块。
Inbox style
在细节部分显示一段行文本。

下面通过一个Demo来实现上述的通知效果,源码可通过文章末尾的链接进行下载。







activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" 
    android:orientation="vertical">

    <Button
        android:id="@+id/bt_notify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/notification" />
    
    <Button
        android:id="@+id/bt_notify_bigview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/notification_bigview" />
    
    <Button
        android:id="@+id/bt_notify_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/notification_progress" />
    
    <Button
        android:id="@+id/bt_notify_custom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/notification_custom" />

</LinearLayout>


MainActivity.java

package com.example.notificationtest;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;

public class MainActivity extends Activity implements OnClickListener {

	private static final String TAG = MainActivity.class.getSimpleName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		findView();
	}

	private void findView() {
		
		Button bt_notify = (Button) findViewById(R.id.bt_notify);
		Button bt_notify_bigview = (Button) findViewById(R.id.bt_notify_bigview);
		Button bt_notify_progress = (Button) findViewById(R.id.bt_notify_progress);
		Button bt_notify_custom = (Button) findViewById(R.id.bt_notify_custom);
		
		bt_notify.setOnClickListener(this);
		bt_notify_bigview.setOnClickListener(this);
		bt_notify_progress.setOnClickListener(this);
		bt_notify_custom.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_notify:
			
			issueSimpleNotification();
			
			break;
		case R.id.bt_notify_bigview:
			
			issueBigViewNotification();
			
			break;
		case R.id.bt_notify_progress:
			
			issueProgressNotification();
			
			break;
		case R.id.bt_notify_custom:
			
			issueNotificationCustom();
			
			break;

		default:
			break;
		}
	}

	private void issueBigViewNotification() {
		
		NotificationCompat.Builder mBuilder =
			    new NotificationCompat.Builder(this)
			    .setSmallIcon(R.drawable.ic_stat_notification)
			    .setContentTitle("6 new messages")
			    .setContentText("twain@android.com")
				.setStyle(new NotificationCompat.InboxStyle()
								.addLine("M.Twain (Google+) Haiku is more than a cert...")
								.addLine("M.Twain Reminder")
								.addLine("M.Twain Lunch?")
								.addLine("M.Twain Revised Specs")
								.addLine("M.Twain ")
								.addLine("Google Play Celebrate 25 billion apps with Goo..")
								.addLine("Stack Exchange StackOverflow weekly Newsl...")
								.setBigContentTitle("6 new message")
								.setSummaryText("mtwain@android.com"))
			    .setTicker("New message")//第一次提示消息的时候显示在通知栏上
				.setNumber(15)
				.setAutoCancel(true);//自己维护通知的消失
		
         Intent resultIntent = new Intent(this, NotifyActivity.class);
         resultIntent.putExtra("msg", "Big View Notification Test");
         resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

         PendingIntent resultPendingIntent =
                 PendingIntent.getActivity(
                 this,
                 0,
                 resultIntent,
                 PendingIntent.FLAG_UPDATE_CURRENT
         );

         //Set the Notification's Click Behavior
         mBuilder.setContentIntent(resultPendingIntent);
         
         // Sets an ID for the notification
         int mNotificationId = 15;
         // Gets an instance of the NotificationManager service
         NotificationManager mNotifyMgr = 
                 (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
         // Builds the notification and issues it.
         mNotifyMgr.notify(mNotificationId, mBuilder.build());
	}

	/**
	 * Custom Notification Layouts
	 */
	private void issueNotificationCustom() {
		
		// 1、创建一个自定义的消息布局 view.xml  
        // 2、在程序代码中使用RemoteViews的方法来定义image和text。然后把RemoteViews对象传到contentView字段  
        RemoteViews remoteView = new RemoteViews(this.getPackageName(),R.layout.custom_notification);  
        remoteView.setImageViewResource(R.id.iv_icon, R.drawable.ic_launcher);  
        remoteView.setTextViewText(R.id.tv_title , "Custom Notification Layout");  
        remoteView.setProgressBar(R.id.pb_progress, 100, 75, false);
        
        Intent resultIntent = new Intent(this, NotifyActivity.class);
        resultIntent.putExtra("msg", "This is a Custom Notification Layout");
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        
        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                this,
                0,
                resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
        
        NotificationCompat.Builder mBuilder =
			    new NotificationCompat.Builder(this)
		        .setSmallIcon(R.drawable.ic_launcher)  
			    .setContentTitle("Custom Notification Layout")
			    .setContent(remoteView)  
			    .setContentIntent(resultPendingIntent)
			    .setDefaults(Notification.DEFAULT_ALL)  
			    .setTicker("new message");
        
     // Sets an ID for the notification
        int mNotificationId = 12;
        // Gets an instance of the NotificationManager service
        NotificationManager mNotifyMgr = 
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Builds the notification and issues it.
        mNotifyMgr.notify(mNotificationId, mBuilder.build());
	}

	/**
	 * 带进度条的 Notification
	 */
	private void issueProgressNotification() {
		
		final NotificationCompat.Builder mBuilder =
			    new NotificationCompat.Builder(this)
			    .setSmallIcon(R.drawable.ic_stat_notification)
			    .setContentTitle("Picture Download")
			    .setContentText("Download in progress");
		
		// Sets an ID for the notification
        final int mNotificationId = 11;
        // Gets an instance of the NotificationManager service
        final NotificationManager mNotifyManager = 
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		
		// Start a lengthy operation in a background thread
		new Thread(
		    new Runnable() {
		        @Override
		        public void run() {
		            int incr;
		            // Do the "lengthy" operation 20 times
		            for (incr = 0; incr <= 100; incr+=5) {
		                    // Sets the progress indicator to a max value, the
		                    // current completion percentage, and "determinate"
		                    // state
		                    mBuilder.setProgress(100, incr, false);
		                    // Displays the progress bar for the first time.
		                    mNotifyManager.notify(mNotificationId, mBuilder.build());
		                        // Sleeps the thread, simulating an operation
		                        // that takes time
		                        try {
		                            // Sleep for 5 seconds
		                            Thread.sleep(1000);
		                        } catch (InterruptedException e) {
		                            Log.d(TAG, "sleep failure");
		                        }
		            }
		            // When the loop is finished, updates the notification
		            mBuilder.setContentText("Download complete")
		            // Removes the progress bar
		                    .setProgress(0,0,false);
		            mNotifyManager.notify(mNotificationId, mBuilder.build());
		        }
		    }
		// Starts the thread by calling the run() method in its Runnable
		).start();
	}

	/**
	 * 简单的 Notification
	 */
	private void issueSimpleNotification() {
		
		Bitmap btm = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_stat_notification);
		
		NotificationCompat.Builder mBuilder =
			    new NotificationCompat.Builder(this)
			    .setSmallIcon(R.drawable.ic_stat_notification)
			    .setLargeIcon(btm)
			    .setContentTitle("Simple Notification Test")
			    .setContentText("I am a Simple Notification")
//			    .setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
			    .setTicker("New message")//第一次提示消息的时候显示在通知栏上
				.setNumber(15)
				.setAutoCancel(true);//自己维护通知的消失
		
		/*
         * Clicking the notification itself displays ResultActivity, which provides
         * UI for snoozing or dismissing the notification.
         * This is available through either the normal view or big view.
         */
         Intent resultIntent = new Intent(this, NotifyActivity.class);
         resultIntent.putExtra("msg", "Simple Notification Test");
         resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

         // Because clicking the notification opens a new ("special") activity, there's
         // no need to create an artificial back stack.
         PendingIntent resultPendingIntent =
                 PendingIntent.getActivity(
                 this,
                 0,
                 resultIntent,
                 PendingIntent.FLAG_UPDATE_CURRENT
         );

         //Set the Notification's Click Behavior
         mBuilder.setContentIntent(resultPendingIntent);
         
         // Sets an ID for the notification
         int mNotificationId = 10;
         // Gets an instance of the NotificationManager service
         NotificationManager mNotifyMgr = 
                 (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
         // Builds the notification and issues it.
         mNotifyMgr.notify(mNotificationId, mBuilder.build());
	}

}


为了保证最好的兼容性,通过NotificationCompat及其子类来创建Notification,明确说是NotificationCompat.Builder,它位于support v4包中。



Demo下载地址:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值