android-學習篇-Service(服務)

簡介

Service 是一種可在後臺執行長時間運行操作而不提供界面的應用組件。

Service 兩種工作狀態:

  • 啓動狀態,主要用於執行後臺計算。startService()
  • 綁定狀態,主要用於其他組件和 Service 的交互。bindService()

Service

Service 是適用於所有服務的基類。擴展此類時,您必須創建用於執行所有服務工作的新線程,因爲服務默認使用應用的主線程,這會降低應用正在運行的任何 Activity 的性能。

package android.app;
public abstract class Service extends ContextWrapper implements ComponentCallbacks2

方法介紹:

// 首次創建服務時,系統會(在調用 onStartCommand() 或 onBind() 之前)調用此方法來執行一次性設置程序。如果服務已在運行,則不會調用此方法。
public void onCreate() 
// 當不再使用服務且準備將其銷燬時,系統會調用此方法。服務應通過實現此方法來清理任何資源,如線程、註冊的偵聽器、接收器等。
public void onDestroy()

// 當另一個組件(如 Activity)請求啓動服務時,系統會通過調用 startService() 來調用此方法。
int onStartCommand(Intent intent, @StartArgFlags int flags, int startId)
// 當另一個組件想要與服務綁定(例如執行 RPC)時,系統會通過調用 bindService() 來調用此方法。
public abstract IBinder onBind(Intent intent);

// 停止服務。此外,其他組件也可通過調用 stopService() 來停止此服務
public final void stopSelf()

// 開啓前臺服務
public final void startForeground(int id, Notification notification)
// 從前臺移除服務。此方法採用布爾值,指示是否需同時移除狀態欄通知。此方法不會停止服務。但是,如果您在服務仍運行於前臺時將其停止,則通知也會隨之移除。
public final void stopForeground(boolean removeNotification)

生命週期

public class ExampleService extends Service {
    int startMode;       // indicates how to behave if the service is killed
    IBinder binder;      // interface for clients that bind
    boolean allowRebind; // 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
    }
}

無論所有服務是通過 startService() 還是 bindService() 創建,系統均會爲其調用 onCreate() 和 onDestroy() 方法。

啓動與綁定方法

package android.content;
public class ContextWrapper extends Context 

public ComponentName startService(Intent service)
public boolean bindService(Intent service, ServiceConnection conn, int flags)

創建 Service

  1. 自定義類繼承 Service
  2. 清單文件中註冊服務

IntentService

IntentService 是 Service 的子類,其使用工作線程逐一處理所有啓動請求。如果您不要求服務同時處理多個請求,此類爲最佳選擇。實現 onHandleIntent(),該方法會接收每個啓動請求的 Intent,以便您執行後臺工作。

前臺服務

前臺服務是用戶主動意識到的一種服務,因此在內存不足時,系統也不會考慮將其終止。前臺服務必須爲狀態欄提供通知,將其放在運行中的標題下方。這意味着除非將服務停止或從前臺移除,否則不能清除該通知。

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
        PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification =
          new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
    .setContentTitle(getText(R.string.notification_title))
    .setContentText(getText(R.string.notification_message))
    .setSmallIcon(R.drawable.icon)
    .setContentIntent(pendingIntent)
    .setTicker(getText(R.string.ticker_text))
    .build();

// 注意:提供給 startForeground() 的整型 ID 不得爲 0。
startForeground(ONGOING_NOTIFICATION_ID, notification);

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章