星期三, 9月 21, 2011

Service(八)

Android應用程式學習筆記

Running a Service in the Foreground

Service不僅只在後台執行,也可以讓service在前台運行,只是這樣的用法比較少。

只要呼叫startForeground()啟動service,就可以讓service在前台執行。這個方法有兩個參數,第一個參數是整數,只用來標識notification。第二個參數是Notification物件。

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);

停止service只要呼叫stopForeground()。


Managing the Lifecycle of a Service

service的生命週期比起activity的簡單多了,然而,密切關注你的service如何產生及如何銷毀的甚至更重要,因為service可以在後台執行,不會被使用者意識到。

service生命週期可以分成兩部分來看:
  • A started service
    Service由其他組件在呼叫startService()方法產生,service會無限地運行,藉著自己呼叫stopSelf()停止自己,或者其他組件呼叫stopService()來停止service,當service停止後,系統銷毀。
  • A bound service
    service由其它組件呼叫bindService()產生,客戶端通過IBinder與service通訊,客戶端可以透過呼叫unbindService()關閉與service的連結。假設許多客戶端綁定在同一個service,當它們都不再與service連結時,系統就會銷毀service。
以下你可以練習來幫助了解生命週期

public class ExampleService extends Service {
    int mStartMode;       // indicates how to behave if the service is killed
    IBinder mBinder;      // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used

    @Override
    public void onCreate() {
        // The service is being created
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // The service is starting, due to a call to startService()
        return mStartMode;
    }
    @Override
    public IBinder onBind(Intent intent) {
        // A client is binding to the service with bindService()
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        // All clients have unbound with unbindService()
        return mAllowRebind;
    }
    @Override
    public void onRebind(Intent intent) {
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }
    @Override
    public void onDestroy() {
        // The service is no longer used and is being destroyed
    }
}



沒有留言:

張貼留言