Android技術精髓-Notification ActivityNotifications
有過Android開發經驗的朋友都應該知道,Notification 是可以顯示給使用者應用程式的正常的UI之外。當系統發出通知,它出現在通知區域中的表徵圖。使用者可以開啟 notification drawer看該通知的詳細資料。同時手機會有如下相應:1、首先狀態列,通知區域持久的表徵圖2、開啟或閃爍device‘s LED3、通過閃爍的背光,播放聲音或震動提醒使用者
notificationActivity代碼:代碼功能是在Activity中通過點擊button 開啟一個task,延遲10秒插入訊息列隊開啟一個notification!
package activitys;import android.app.Activity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.widget.Button;import android.widget.Toast;public class NotificationActivity extends Activity implements View.OnClickListener {private static final int NOTE_ID = 100;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);Button button = new Button(this);button.setText("Post New Notification");button.setOnClickListener(this);setContentView(button);}@Overridepublic void onClick(View v) {handler.postDelayed(task, 10000);Toast.makeText(this, "Notification will post in 10 seconds",Toast.LENGTH_SHORT).show();}private Handler handler = new Handler();private Runnable task = new Runnable() {@Overridepublic void run() {NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);Intent launchIntent = new Intent(getApplicationContext(),Test.class);PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);Notification note = new Notification(R.drawable.icon,"Something Happened", System.currentTimeMillis());note.setLatestEventInfo(getApplicationContext(), "Finished!","Click Here!", contentIntent);note.defaults |= Notification.DEFAULT_SOUND;note.flags |= Notification.FLAG_AUTO_CANCEL;manager.notify(NOTE_ID, note);}};}
postDelayed(Runnable r, long delayMillis)
延時delayMillis毫秒 將Runnable插入訊息列隊,Runnable將在handle綁定的線程中運行。post 是立即插入訊息列隊,當訊息列隊處理到該訊息時才運行
PendingIntent
我們知道Intent 是及時啟動,intent 隨所在的activity 消失而消失。
PendingIntent 是對intent的封裝,通常通過getActivity,getBroadcast ,getService來得到pendingintent的執行個體pendingintent中 儲存有當前App的Context,使它賦予外部App一種能力,使得外部App可以如同當前App一樣的執行pendingintent裡的 Intent,就算在執行時當前App已經不存在了,也能通過存在pendingintent裡的Context照樣執行Intent。另外還可以處理intent執行後的操作。常和alermanger 和notificationmanager一起使用。
Intent一般是用作Activity、Sercvice、BroadcastReceiver之間傳遞資料,而Pendingintent,一般用在 Notification上,可以理解為順延強制的intent,PendingIntent是對Intent一個封裝。
總而言之,PendingIntent就是一個可以在滿足一定條件下執行的Intent,它相比於Intent的優勢在於自己攜帶有Context對象,這樣他就不必依賴於某個activity才可以存在。
Notification
通知類Notificationpublic class
notification
extends Object
implements Parcelable
1、建立Notification
通過NotificationManager的notify(int,Notification)方法來啟動Notification。
第一個參數唯一的標識該Notification,第二個參數就是Notification對象。
2、更新Notification
調用Notification的setLatestEventInfo方法來更新內容,然後再調用NotificationManager的notify()方法即可。(具體可以看下面的執行個體)
3、刪除Notification
通過NotificationManager的cancel(int)方法,來清除某個通知。其中參數就是Notification的唯一標識ID。
當然也可以通過cancelAll()來清除狀態列所有的通知。
4、Notification設定(震動、鈴聲等)
Notification範例程式碼:
//建立狀態列通知 baseNF=newNotification(); //設定通知在狀態列顯示的表徵圖 baseNF.icon=R.drawable.icon; //通知時在狀態列顯示的內容 baseNF.tickerText="YouclickedBaseNF!"; //通知的預設參數DEFAULT_SOUND,DEFAULT_VIBRATE,DEFAULT_LIGHTS. //如果要全部採用預設值,用DEFAULT_ALL. //此處採用預設聲音 baseNF.defaults=Notification.DEFAULT_SOUND; //第二個參數:下拉狀態列時顯示的訊息標題expandedmessagetitle //第三個參數:下拉狀態列時顯示的訊息內容expandedmessagetext //第四個參數:點擊該通知時執行頁面跳轉 baseNF.setLatestEventInfo(Lesson_10.this,"Title01","Content01",pd); //發出狀態列通知 //ThefirstparameteristheuniqueIDfortheNotification //andthesecondistheNotificationobject. nm.notify(Notification_ID_BASE,baseNF);
添加Notification聲音:
1、如果要採用預設聲音,只要使用default就可以了。
baseNF.defaults=Notification.DEFAULT_SOUND;
2、如果要使用自訂聲音,那麼就要用到sound了。如下:
notification.sound=Uri.parse("file:///sdcard/notification/ringer.mp3");
3、如果想用系統內建的鈴聲,可以這樣:
notification.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI,"6");
(如果default、sound同時出現,那麼sound無效,會使用預設鈴聲。 )
4、預設情況下,通知的聲音播放一遍就會結束。如果你想讓聲音迴圈播放,需要為flags參數加上FLAG_INSISTENT。這樣聲音會到使用者響應才結束,比如下拉狀態列。
notification.flags|=notification.FLAG_INSISTENT;
Notification添加震動 :
1、預設的震動方式。
notification.defaults|=Notification.DEFAULT_VIBRATE;
2、自己定義震動形式,這邊需要用到Long型數組。
long[]vibrate={0,100,200,300}; notification.vibrate=vibrate; Long型數組中,第一個參數是開始震動前等待的時間,第二個參數是第一次震動的時間,第三個參數是第二次震動的時間,以此類推,隨便定義多長的數組。但是採用這種方法,沒有辦法做到重複震動。
同樣,如果default、vibrate同時出現時,會採用預設形式。
注意添加許可權:
Notification添加閃光:
1、預設的燈光
notification.defaults|=Notification.DEFAULT_LIGHTS;
2、自訂燈光:
notification.ledARGB=0xff00ff00; notification.ledOnMS=300; notification.ledOffMS=1000; notification.flags|=Notification.FLAG_SHOW_LIGHTS;
其中ledARGB表示燈光顏色、ledOnMS亮期間、ledOffMS暗的時間。
Notification其他有用的設定:
flags: Notification.FLAG_INSISTENT;//讓聲音、震動無限迴圈,直到使用者響應 Notification.FLAG_AUTO_CANCEL;//通知被點擊後,自動消失 Notification.FLAG_NO_CLEAR;//點擊'Clear'時,不清楚該通知(QQ的通知無法清除,就是用的這個 //自訂下拉視圖,比如下載軟體時,顯示的進度條。 Notificationnotification=newNotification(); notification.icon=R.drawable.icon; notification.tickerText="Custom!"; RemoteViewscontentView=newRemoteViews(getPackageName(),R.layout.custom); contentView.setImageViewResource(R.id.image,R.drawable.icon); contentView.setTextViewText(R.id.text,"Hello,thismessageisinacustomexpandedview"); notification.contentView=contentView; //使用自訂下拉視圖時,不需要再調用setLatestEventInfo()方法 //但是必須定義contentIntent notification.contentIntent=pd; nm.notify(3,notification);
使用自訂的Notification
要建立一個自訂的Notification,可以使用RemoteViews。要定義自己的擴充訊息,首先要初始化一個RemoteViews對象,然後將它傳遞給Notification的contentView欄位,再把PendingIntent傳遞給contentIntent欄位。以下範例程式碼是完整步驟:
1、建立一個自訂的訊息布局 view.xml
//2、在程式碼中使用RemoteViews的方法來定義image和text。然後把RemoteViews對象傳到contentView欄位
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.view);contentView.setImageViewResource(R.id.image,R.drawable.icon);contentView.setTextViewText(R.id.text,”Hello,this message is in a custom expanded view”);notification.contentView = contentView;//3、為Notification的contentIntent欄位定義一個Intent(注意,使用自訂View不需要setLatestEventInfo()方法)Intent notificationIntent = new Intent(this,Main.class);PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);notification.contentIntent = contentIntent;
//4、發送通知
mNotificationManager.notify(2,notification);//以下是全部範例程式碼//建立一個NotificationManager的引用String ns = Context.NOTIFICATION_SERVICE;NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);//定義Notification的各種屬性int icon = R.drawable.icon; //通知表徵圖CharSequence tickerText = "Hello"; //狀態列顯示的通知文本提示long when = System.currentTimeMillis(); //通知產生的時間,會在通知資訊裡顯示//用上面的屬性初始化NofificationNotification notification = new Notification(icon,tickerText,when);RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.view);contentView.setImageViewResource(R.id.image, R.drawable.iconempty);contentView.setTextViewText(R.id.text, "Hello,this is JC");notification.contentView = contentView;Intent notificationIntent = new Intent(this,Main.class);PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);notification.contentIntent = contentIntent;//把Notification傳遞給NotificationManagermNotificationManager.notify(0,notification);
2014.1.22