Android中Intent,service,broadcast應用淺析(一)
典型的Android應用程式由兩部分構成,一個是在前台啟動並執行Activity和View,一個就是在後台啟動並執行Intent 和Service對象,還有一種是是廣播接收器,BroadCastReceiver,我們通常啟動一個service(服務)對象或者發送一個廣播,都是由Intent 來啟動的.
首先來看下怎麼用Intent來啟動一個服務:
寫了一個小例子,在首頁面上有兩個按鈕,一個點擊是啟動服務,一個點擊是取消服務,看了介面,再看一下介面,在看一下原始碼的.
關於服務需要說明的是:服務中只有onCreate,onStart,和onStop方法,當第一次啟動服務的時候調用的是onCreate,onStart方法,停止服務時調用onStop方法,完了之後再啟動服務就只需要調用onStart方法了.
public class Activity01 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startService = (Button) findViewById(R.id.startBtn);
startService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(Activity01.this,
BackgroundService.class));
}
});
Button stopService = (Button) findViewById(R.id.stopBtn);
stopService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(Activity01.this, BackgroundService.class));
}
});
}
}
我現在寫的這個小服務的功能是滿足時間條件後重新整理狀態列,具體的說,就是啟動服務之後開始計算時間,當時間過了一定的時間點之後就重新整理狀態列,因為之前要在程式中做這一塊,就寫了這樣的一個小例子.
先看代碼中onCreate方法,聲明了一個通知欄管理的對象,然後用了一個handler,這個handler收到message之後靜態變數seconds加一,然後更新狀態列。
@Override
public void onCreate() {
super.onCreate();
notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
seconds++;
updateNotification(seconds);
break;
}
super.handleMessage(msg);
}
};
timer = new Timer(false);
}
但是handler是怎樣收到message的呢?這是我們在onStart中建立了一個timer的對象,可以看代碼,onStart方法中向通知欄發送一個訊息,說明已經啟動服務,然後調用run方法,每個一秒鐘向handler發送一個訊息.handler接收到訊息後執行的代碼已經在onCreate中說過
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
displayNotificationMessage("starting Background Service");
timer.schedule(new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}, 1000, 1000);
}
當我去停止服務的時候,向通知欄中發動一個訊息,說明停止服務,然後重新置標記服務已經開始了多長時間的變數為0,同時用timer.cancel()方法來停止timer的運行。
@Override
public void onDestroy() {
super.onDestroy();
displayNotificationMessage("stopping Background Service");
seconds = 0;
timer.cancel();
}
向狀態列發送資訊的方法,需要說明的就是這個PendingIntent,剛開始的時候很不理解這個東西,後來終於搞明白了,Intent是發送出去一個任務,我們向狀態列中發送一個訊息,狀態列下拉點擊的時候我們要讓他有什麼樣的反應,就是需要用PendingIntent來定義,相當於PendingIntent定義的是這個操作被觸發的時候需要的指示操作,通俗理解,Intent相當於你跟別人發送一個直接命令,說讓別人直接做什麼.PendingIntent相當於你給別人一個命令,命令中告訴他當有緊急事件發生的時候做什麼,總之有點難理解了.
private void displayNotificationMessage(String message) {
Notification notification = new Notification(R.drawable.icon, message,
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Activity01.class), 0);
notification.setLatestEventInfo(this, "Background Service", message,
contentIntent);
notificationMgr.notify(R.id.app_notification_id, notification);
}
關於廣播和服務還有Intent更加詳細的說明還有後續.
本文出自 “HDDevTeam” 部落格