Notification用法

本文介紹了Notification的用法。

1、示例演示用法

1)NotificationActivity.java

/**
 * 演示了Notification的用法
 * Notification的創建、顯示、刪除
 * 通知欄點擊Notification打開Activity、Service、Broadcast
 * 直接new一個Notification或通過Notification.Builder來創建
 * 自定義Notification的視圖並點擊交互
 */
public class NotificationActivity extends Activity {
	private BroadcastReceiver mBroadcastReceiver;
	private NotificationManager mNotificationManager;
	private int NOTIFICATION_ID = 0x007;
	private int NOTIFICATION_ID2 = 0x008;
	private int NOTIFICATION_ID3 = 0x009;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}
	private void init(){
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(NewBroadcastReceiver.ACTION_NOTIFICATION);
		intentFilter.addAction(NewBroadcastReceiver.ACTION_NOTIFICATION2);
		mBroadcastReceiver = new NewBroadcastReceiver();
		registerReceiver(mBroadcastReceiver, intentFilter);
		
		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		findViewById(R.id.btn).setOnClickListener(mOnClickListener);
		findViewById(R.id.btn_direct).setOnClickListener(mOnClickListener);
		findViewById(R.id.btn_custom).setOnClickListener(mOnClickListener);
		//API level 11
		Notification.Builder builder = new Notification.Builder(this);
		builder.setSmallIcon(R.drawable.ic_launcher)//status bar
			.setTicker("猥瑣不")//status bar
			.setWhen(System.currentTimeMillis())//the time the event occurred
			.setDefaults(Notification.DEFAULT_SOUND)
			.setContentTitle("石鑫")
			.setContentText("小李飛刀")
			.setContentInfo("美好的回憶")
			.setContentIntent(PendingIntent.getActivity(this, 
					0, new Intent(this, NewActivity.class), 0))//startActivity
//			.setContentIntent(PendingIntent.getBroadcast(this, 0, 
//				new Intent(NewBroadcastReceiver.ACTION_NOTIFICATION), 0))//sendBroadcastReceiver
//			.setContentIntent(PendingIntent.getService(this, 0, 
//				new Intent(this, NewService.class), 0))//startService
			.setAutoCancel(true);//dismiss when touched
		Notification notification = builder.getNotification();//v16用build
		mNotificationManager.notify(NOTIFICATION_ID, notification);
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}
	private OnClickListener mOnClickListener = new OnClickListener() {
		@SuppressWarnings("deprecation")
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn:
				mNotificationManager.cancel(NOTIFICATION_ID);//通過ID刪除Notification
				mNotificationManager.cancel(NOTIFICATION_ID2);
				mNotificationManager.cancel(NOTIFICATION_ID3);break;
			case R.id.btn_direct:
				Notification notification = new Notification(R.drawable.ic_launcher, 
					"monkey", System.currentTimeMillis());
				//給Notification添加sound
				Uri ringURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
				notification.sound = ringURI;
				//給Notification添加Vibration
				long[] vibrate = new long[]{1000,1000,1000,1000,1000};
				notification.vibrate = vibrate;
				
				notification.setLatestEventInfo(NotificationActivity.this, "Activity", "launch an activity", 
					PendingIntent.getActivity(NotificationActivity.this, 0, 
					new Intent(NotificationActivity.this, NewActivity.class), 0));
				mNotificationManager.notify(NOTIFICATION_ID2, notification);break;
			case R.id.btn_custom:
				Notification notification2 = new Notification(R.drawable.ic_launcher, 
						"monkey", System.currentTimeMillis());
				RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.notification);
				notification2.contentView = remoteView;
				notification2.contentIntent = PendingIntent.getActivity(NotificationActivity.this, 0, 
					new Intent(NotificationActivity.this, NewActivity.class), 0);
				notification2.contentView.setTextViewText(R.id.txt, "騷包");
				notification2.contentView.setProgressBar(R.id.progressbar, 1000, 400, false);
				//註冊及在廣播中處理點擊事件
				notification2.contentView.setOnClickPendingIntent(R.id.img, 
					PendingIntent.getBroadcast(NotificationActivity.this, 0, 
					new Intent(NewBroadcastReceiver.ACTION_NOTIFICATION2), 0));
				mNotificationManager.notify(NOTIFICATION_ID3, notification2);
			default:
				break;
			}
		}
	};
}
2)activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button 
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hit me"
        android:layout_gravity="center"/>
    <Button 
        android:id="@+id/btn_direct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="direct"
        android:layout_gravity="center"/>
    <Button 
        android:id="@+id/btn_custom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="custom"
        android:layout_gravity="center"/>
</LinearLayout>
3)NewActivity.java
public class NewActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i(getClass().getSimpleName(), "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new);
	}
}
4)activity_new.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="歡迎步入星光大道"/>
</RelativeLayout>
5)NewBroadcastReceiver.java
public class NewBroadcastReceiver extends BroadcastReceiver {
	/**使用4次,定義、註冊、發送、接收*/
	public static final String ACTION_NOTIFICATION = "action.NOTIFICATION";
	public static final String ACTION_NOTIFICATION2 = "action.NOTIFICATION2";
	@Override
	public void onReceive(Context context, Intent intent) {
		if(ACTION_NOTIFICATION.equals(intent.getAction())){
			Log.i(getClass().getSimpleName(), "onReceive");
		}else if(ACTION_NOTIFICATION2.equals(intent.getAction())){
			Toast.makeText(context, "輕點好嗎", Toast.LENGTH_SHORT).show();
		}
	}
}
6)NewService.java
public class NewService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		//只有Service.onBind(Intent)覆寫
		return null;
	}

	@Override
	public void onCreate() {
		Log.i(getClass().getSimpleName(), "onCreate");
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(getClass().getSimpleName(), "onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}
}
7)notification.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView 
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:src="@drawable/ic_launcher"/>
    <TextView 
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"/>
    <ProgressBar 
        android:id="@+id/progressbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/img"
        android:layout_alignParentBottom="true"
        style="@android:style/Widget.ProgressBar.Horizontal"/>
</RelativeLayout>
8)AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.qinuli.notificationtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.VIBRATE"/>
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.qinuli.notificationtest.NotificationActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NewActivity"></activity>
        <service android:name=".NewService"/>
    </application>

</manifest>

發佈了56 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章