Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Service 深入講解(一):用法、通訊、銷毀與前台 Service

編輯:Android 開發實例

大多數 Android 開發者對 Service 這個名詞都不陌生。作為四大元件之一,它在每個應用裡都扮演著重要角色:主要負責在後台處理耗時邏輯,或執行需要長期存活的任務;必要時,甚至能在程式畫面關掉之後繼續運行。

但「聽過」和「真正掌握」是兩件事。今天我們就來把 Service 一次梳理清楚,希望讀完之後你對它的理解能再深一層。

Service 的基本用法

最基本的用法自然是如何啟動一個 Service。啟動方式與啟動 Activity 很類似,都要靠 Intent 來完成,我們直接看例子。

新建一個 Android 專案,命名為 ServiceTest(這裡選用 4.0 的 API)。然後建立一個 MyService 繼承自 Service,覆寫 onCreate()、onStartCommand() 與 onDestroy():

public class MyService extends Service {

    public static final String TAG = "MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() executed");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() executed");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy() executed");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

這裡我們只在三個方法中各自印了一句話,沒有做其他任何事。

接著編輯 activity_main.xml 作為主佈局,放入兩個按鈕:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service" />

    <Button
        android:id="@+id/stop_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service" />

</LinearLayout>

然後在 MainActivity 中寫入啟動與停止的邏輯:

public class MainActivity extends Activity implements OnClickListener {

    private Button startService;
    private Button stopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService = (Button) findViewById(R.id.start_service);
        stopService = (Button) findViewById(R.id.stop_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start_service:
            Intent startIntent = new Intent(this, MyService.class);
            startService(startIntent);
            break;
        case R.id.stop_service:
            Intent stopIntent = new Intent(this, MyService.class);
            stopService(stopIntent);
            break;
        default:
            break;
        }
    }
}

邏輯非常直白:Start Service 的點擊事件裡建構 Intent 並呼叫 startService();Stop Service 則呼叫 stopService()。

另外別忘了,專案中的每個 Service 都必須在 AndroidManifest.xml 中註冊:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.servicetest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        ......
        <service android:name="com.example.servicetest.MyService" >
        </service>
    </application>

</manifest>

執行專案並點擊 Start Service,LogCat 會印出 onCreate() executed 與 onStartCommand() executed。也就是說,啟動一個 Service 時,會依序呼叫這兩個方法。

那如果我們再點一次 Start Service 呢?這次只有 onStartCommand() 被執行,onCreate() 沒有。原因在於 onCreate() 只在 Service 第一次被建立時呼叫;只要該 Service 已經存在,無論呼叫多少次 startService(),onCreate() 都不會再執行。你可以多點幾次驗證,每次只會看到 onStartCommand() 的日誌。

我們也可以到手機的應用程式管理介面確認 MyService 是否正在運行——即使它內部什麼邏輯都沒跑,它也確實是運行狀態。回到程式後,點擊 Stop Service 就能把它停掉。

Service 和 Activity 通訊

上面那種用法裡,Service 與 Activity 的關係其實很淡:Activity 只是通知一聲「你可以啟動了」,然後 Service 就去做自己的事。有沒有辦法讓兩者關係更緊密一些,例如由 Activity 指定 Service 要執行什麼任務?當然可以,只要讓它們建立關聯即可。

觀察 MyService 的程式碼,你會發現 onBind() 一直沒被用到——它就是為了建立關聯而存在的。修改 MyService:

public class MyService extends Service {

    public static final String TAG = "MyService";

    private MyBinder mBinder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() executed");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() executed");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy() executed");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    class MyBinder extends Binder {

        public void startDownload() {
            Log.d("TAG", "startDownload() executed");
            // 執行具體的下載任務
        }
    }
}

這裡新增了一個 MyBinder 類別繼承自 Binder,並在其中加入 startDownload() 方法代表在後台執行下載(這裡只是測試,所以只印一行日誌)。

接著在 activity_main.xml 中補上綁定與解除綁定的按鈕:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service" />

    <Button
        android:id="@+id/stop_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service" />

    <Button
        android:id="@+id/bind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bind Service" />

    <Button
        android:id="@+id/unbind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Unbind Service" />

</LinearLayout>

然後修改 MainActivity,讓它與 MyService 建立關聯:

public class MainActivity extends Activity implements OnClickListener {

    private Button startService;
    private Button stopService;
    private Button bindService;
    private Button unbindService;

    private MyService.MyBinder myBinder;

    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyService.MyBinder) service;
            myBinder.startDownload();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService = (Button) findViewById(R.id.start_service);
        stopService = (Button) findViewById(R.id.stop_service);
        bindService = (Button) findViewById(R.id.bind_service);
        unbindService = (Button) findViewById(R.id.unbind_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start_service:
            Intent startIntent = new Intent(this, MyService.class);
            startService(startIntent);
            break;
        case R.id.stop_service:
            Intent stopIntent = new Intent(this, MyService.class);
            stopService(stopIntent);
            break;
        case R.id.bind_service:
            Intent bindIntent = new Intent(this, MyService.class);
            bindService(bindIntent, connection, BIND_AUTO_CREATE);
            break;
        case R.id.unbind_service:
            unbindService(connection);
            break;
        default:
            break;
        }
    }
}

這裡先建立一個 ServiceConnection 匿名類別,覆寫 onServiceConnected() 與 onServiceDisconnected(),兩者分別在建立關聯與解除關聯時被呼叫。在 onServiceConnected() 中,我們向下轉型取得 MyBinder 實例——有了它,Activity 與 Service 的關係就非常緊密了:Activity 可以按場景呼叫 MyBinder 中任何 public 方法,真正做到「Activity 指揮,Service 執行」。

當然,此時兩者還沒關聯起來,這是在 Bind Service 的點擊事件中完成的:建構 Intent 後呼叫 bindService()。這個方法接收三個參數,第一個是 Intent,第二個是 ServiceConnection 實例,第三個是旗標;傳入 BIND_AUTO_CREATE 表示建立關聯時自動建立 Service,這會觸發 onCreate(),但不會執行 onStartCommand()。

若想解除關聯,呼叫 unbindService() 即可,也就是 Unbind Service 按鈕做的事。

重新執行並點擊 Bind Service,LogCat 中可以看到對應的日誌輸出。另外要注意:Service 在整個應用範圍內是通用的,也就是說 MyService 不只可以跟 MainActivity 關聯,也可以跟任何其他 Activity 關聯,而且它們拿到的會是同一個 MyBinder 實例。

如何銷毀 Service

最簡單的情況前面已經看過:Start Service 啟動,Stop Service 停止,MyService 就被銷毀了。

那如果是點 Bind Service 呢?由於綁定時指定了 BIND_AUTO_CREATE,Service 同樣會被建立,這時只要點一下 Unbind Service 解除關聯即可。

先點 Bind Service 再點 Unbind Service,日誌會顯示 Service 的啟動與銷毀過程。

比較值得留意的是:如果你「既點了 Start Service,又點了 Bind Service」,那麼無論單獨點 Stop Service 還是 Unbind Service,Service 都不會被銷毀,必須兩個都點過才會真的銷毀。也就是說,Stop Service 只會讓 Service 停止,Unbind Service 只會解除與 Activity 的關聯;一個 Service 必須在「沒有任何 Activity 關聯」且「已處於停止狀態」時才會被銷毀。

為了驗證,我們在 Stop Service 與 Unbind Service 的點擊事件裡各加一行日誌:

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.start_service:
        Intent startIntent = new Intent(this, MyService.class);
        startService(startIntent);
        break;
    case R.id.stop_service:
        Log.d("MyService", "click Stop Service button");
        Intent stopIntent = new Intent(this, MyService.class);
        stopService(stopIntent);
        break;
    case R.id.bind_service:
        Intent bindIntent = new Intent(this, MyService.class);
        bindService(bindIntent, connection, BIND_AUTO_CREATE);
        break;
    case R.id.unbind_service:
        Log.d("MyService", "click Unbind Service button");
        unbindService(connection);
        break;
    default:
        break;
    }
}

重新執行,先點 Start Service 再點 Bind Service,此時 Service 已啟動並與 Activity 建立關聯。接著點 Stop Service,Service 不會銷毀;再點 Unbind Service,Service 才會銷毀。

因此請始終記得:在 onDestroy() 中清理掉不再使用的資源,避免 Service 銷毀後仍有物件佔著記憶體。

Service 和 Thread 的關係

不少初學者都有這個疑問:Service 和 Thread 到底有什麼關係?什麼時候該用哪一個?答案可能出乎意料——兩者之間沒有任何關係。

之所以常被混為一談,是因為 Service 的「後台」這個概念。Thread 大家都懂,用來開子執行緒跑耗時操作,不阻塞主執行緒。而我們直覺上總覺得 Service 是處理後台任務的,耗時操作放裡面應該也沒問題,於是就產生了混淆。

但如果我告诉你:Service 其實是運行在主執行緒裡的,你還會覺得它和 Thread 有關係嗎?我們來看這個有點殘酷的事實。

在 MainActivity 的 onCreate() 中加入一行印出目前執行緒 id 的語句:

Log.d("MyService", "MainActivity thread id is " + Thread.currentThread().getId());

並在 MyService 的 onCreate() 中也加入同樣的語句:

Log.d("MyService", "MyService thread id is " + Thread.currentThread().getId());

重新執行並點擊 Start Service,你會發現兩者的執行緒 id 完全相同。這證實了 Service 確實跑在主執行緒上——也就是說,如果你在 Service 裡寫了非常耗時的程式碼,ANR 是必然的。

你可能會想:那不是沒什麼用?其實關鍵在於不要把「後台」和「子執行緒」混在一起,這是兩個完全不同的概念。Android 所說的後台,指的是「運行完全不依賴 UI」:即使 Activity 被銷毀、程式被關閉,只要進程還在,Service 就能繼續跑。例如某些應用需要與伺服器永遠保持心跳連線,就很適合用 Service。

那問題來了:既然 Service 跑在主執行緒,一直在這裡做心跳連線難道不會卡住嗎?當然會。但這不是問題——我們可以在 Service 裡再開一個子執行緒,把耗時邏輯放進去就好。

既然如此,為什麼不乾脆在 Activity 裡開子執行緒?因為 Activity 很難控制 Thread:Activity 銷毀之後,就再也拿不回先前建立的子執行緒實例;而且在一個 Activity 中建立的執行緒,另一個 Activity 也無法操作。Service 則不同,所有 Activity 都能與它建立關聯並操作其中的方法,即使 Activity 被銷毀,之後重新關聯又能取得原有 Binder 實例。所以用 Service 承載後台任務,Activity 可以放心 finish,不必擔心後續失控。

一個比較標準的 Service 寫法如下:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            // 開始執行後台任務
        }
    }).start();
    return super.onStartCommand(intent, flags, startId);
}

class MyBinder extends Binder {

    public void startDownload() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 執行具體的下載任務
            }
        }).start();
    }
}

建立前台 Service

Service 幾乎都在後台默默工作,但它的系統優先級其實偏低。當系統記憶體不足時,正在後台運行的 Service 有可能被回收。如果你希望 Service 能一直存活、不因記憶體不足而被回收,就可以考慮前台 Service。

前台 Service 與普通 Service 最大的差別,在於狀態列會一直有一個運行中的圖示,下拉後能看到更詳細的資訊,效果很類似通知。當然,使用前台 Service 的理由不一定只是為了避免被回收——有些產品因為需求本身就必須用它,例如墨跡天氣在後台更新資料的同時,還會在狀態列持續顯示當前天氣。

實作起來並不複雜,修改 MyService:

public class MyService extends Service {

    public static final String TAG = "MyService";

    private MyBinder mBinder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        Notification notification = new Notification(R.drawable.ic_launcher,
                "有通知到來", System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
        notification.setLatestEventInfo(this, "這是通知的標題", "這是通知的內容",
                pendingIntent);
        startForeground(1, notification);
        Log.d(TAG, "onCreate() executed");
    }

    .....
}

這裡只改了 onCreate():先建立一個 Notification 物件,呼叫 setLatestEventInfo() 為它初始化版面與資料,並設定點擊後開啟 MainActivity;接著呼叫 startForeground(),MyService 就變成前台 Service,通知圖示也會一起顯示出來。

重新執行並點擊 Start Service 或 Bind Service,MyService 就會以前台模式啟動,狀態列會出現一個常駐圖示,下拉後可看到通知的完整內容。

由於篇幅關係,本篇就先寫到這裡。目前 Service 的多數重要知識點都已經梳理完畢,下一篇會接著介紹剩下那個既重要又相對複雜的主題——遠程 Service 的使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved