Notification (通知)的 新版和舊版用法
一、先來看舊版,Api 11 之前的用法:
NotificationManager manager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.mipmap.ic_launcher, "This is bitch.", System.currentTimeMillis());
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(this, "This is ContentTitle","This is ContentText", pi);
manager.notify(1, notification);
manager.cancel(1); // 清除通知欄上的内容,這裡的 1 是通知的Id
二、Api 11之後的用法:
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(MainActivity.this);
PendingIntent contentIntent = PendingIntent.getActivities(MainActivity.this, 0,
new Intent[]{new Intent(MainActivity.this, MainActivity.class)}, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.mipmap.ic_launcher) //設定狀态欄裡面的圖示(小圖示)
// .setLargeIcon(BitmapFactory.decodeResource(resource, R.mipmap.ic_launcher)) //下拉下拉清單裡面的圖示(大圖示)
.setTicker("This is bitch.") //設定狀态欄的顯示的資訊
.setWhen(System.currentTimeMillis()) //設定時間發生時間
.setAutoCancel(true) //設定可以清除
.setContentTitle("This is ContentTitle") //設定下拉清單裡的标題
.setContentText("This is ContentText"); //設定上下文内容
Notification notification = builder.getNotification();
Notification notification = builder.geNotification(); // 這裡的方法其實已經被廢棄了,它裡面的源代碼就是如下這樣
/**
* @deprecated Use {@link #build()} instead.
*/
@Deprecated
public Notification getNotification() {
return build();
}
官方給出的也是用bulid()方法取代它,但是直接用build()方法的話我的Api跟它有問題,直接調用廢棄的getNotification()方法就可以了
另外Notification 還有很多其他常用屬性,比如震動,響鈴,控制手機前置的LED燈(這裡需要在 AndroidManifest.xml中設定權限:
<uses-permission android:name="android.permission.VIBRATE" /> ):
● 震動:
long[] vibrates = new Long[]{0, 1000, 1000, 1000,...}; // 第零個值表示手機靜止的時長,第一個值表示手機震動的時長,
// 第二個值表示手機靜止的時長,依次類推,機關是毫秒
notification.vibrate = vibrates;
● 響鈴:
Uri soundUri = Uri.fomrFile(new File("/system/media/audio/ringtones/Basic_tone_ogg")); // 這個是手機自帶的音頻檔案
notification.sound = soundUri;
● 控制 LED 燈
// 以綠光一閃一閃的效果
notification.ledARGB = Color.GREEN;
notification.ledOnMS = 1000;
notification.ledOffMS = 1000;
notification.flags = Notification.FLAG_SHOW_LIGHTS;
// 系統預設,它會自己去判斷應該放什麼鈴聲
notification.defaults = Notification.DEFAULT_ALL;