Notification (通知)的 新版和舊版用法


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();
manager.notify(1, notification);
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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM