本地服務
所謂本地服務,其實就是完全服務於一個進程的組件。本地服務的這種特性決定了它有特別的啟動方式。通常這類服務的典型案例,就是郵件輪詢。
調用Context.startService()啟動服務
package net.bpsky;
import Android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class DoudingService extends Service {
private NotificationManager notificationMgr;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
displayNotificationMessage("Starting Background Service!");
Thread thr = new Thread(null,new ServiceWorker(),"BackgroundService");
thr.start();
}
class ServiceWorker implements Runnable{
public void run(){
// bla bla bla...
}
}
@Override
public void onDestroy(){
displayNotificationMessage("Stopping Background Service");
super.onDestroy();
}
@Override
public void onStart(Intent intent,int startId){
super.onStart(intent, startId);
}
private void displayNotificationMessage(String message){
Notification notification = new Notification(R.drawable.note,message,System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this,0,new Intent(this,FeedActivity.class),0);
notification.setLatestEventInfo(this, "background Service", message, contentIntent);
notificationMgr.notify(R.id.app_notification_id,notification);
}
}
支持onBind()方法的,就是遠程服務。遠程服務並不是說一定要遠程訪問,而是支持(RPC,Remote Procedure Call,遠程過程調用)。這類服務的典型案例就是應用程序之間執行通信。比如:路由服務,將信息轉發至其它應用程序。遠程服務最重要的一個特性就是需要AIDL(Android Interface Definition Language)向客戶端定義自身。
下面我們來作一個調用模擬,可以看到圖例大概的結構是這樣的。
服務端(RPCService)