您的位置:首頁>正文

安卓Service完全解析(上)

版權聲明:本文出自汪磊的博客, 轉載請務必注明出處。

關於安卓Service相信很多安卓開發者都聽說過, 作為安卓四大元件之一, 即使不經常用也應該聽說過, 但並不是每一個人都掌握的特別詳細, 全面。 那麼今天我將帶大家全面瞭解一下Service.希望對您有所幫助。

什麼是Service?

先來看一下官方定義:

A Serviceis an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

翻譯過來就是:Service是一個沒有使用者介面的在後臺運行執行耗時操作的應用組件。 其他應用元件能夠啟動Service,

並且當用戶切換到另外的應用場景, Service將持續在後臺運行。 另外, 一個元件能夠綁定到一個service與之交互(IPC機制),

例如,

一個service可能會處理網路操作, 播放音樂, 操作檔I/O或者與內容提供者(content provider)交互, 所有這些活動都是在後臺進行。

簡單說Service就是一個不依附介面可以在後臺長期執行耗時操作的元件。

Service基本用法

接下來瞭解一下Service的啟動以及生命週期, 下面通過一個簡單實例來學習一下。

新建一個MyService繼承自Service, 並重寫父類的onCreate、onStartCommand和onDestroy方法, 如下所示:

1 public class MyService extends Service { 2 3 @Override 4 public IBinder onBind(Intent arg0) { 5 return null; 6 } 7 8 @Override 9 public void onCreate {10 Log.i("WLService", "onCreate"); 11 super.onCreate;12 }13 14 @Override15 public int onStartCommand(Intent intent, int flags, int startId) {16 Log.i("WLService", "onStartCommand"); 17 return super.onStartCommand(intent, flags, startId);18 }19 20 @Override21 public void onDestroy {22 Log.i("WLService", "onDestroy"); 23 super.onDestroy;24 }25 26 }

然後打開專案佈局檔, 添加啟動, 關閉Service按鈕, 如下:

1 7 8
同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示