Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 四大組件之 Service 詳解

編輯:Android 程式設計入門

本文詳細梳理 Service 的生命週期、進程優先級、使用注意事項,以及本地服務與跨進程通信(AIDL)的具體用法。

一、Service 的生命週期

  • onCreate:第一次創建 Service 時調用。
  • onStartCommand:啟動 Service 時調用。
  • onStart(此方法在 API level 5 中已廢棄,應改用 onStartCommand(Intent, int, int))。
  • onDestroy:銷毀時調用。

二、進程優先級(由高到低)

  1. Foreground process 前台進程:用戶正在操作的應用進程。
  2. Visible process 可視進程:用戶可以看到但無法操作的應用進程。
  3. Service process 服務進程:後台運行的服務所在進程(若有 Activity 在前台,則屬於前台進程)。
  4. Background process 後台進程:最小化、託管到後台運行的應用。
  5. Empty process 空進程:已退出、沒有任何任務運行的進程。

其中後台進程與空進程是最常被系統回收的兩類。

三、使用注意事項

1. Service 裡能否寫耗時操作?不能。若有耗時操作可能導致 ANR。原因是:Service 這些回調方法的代碼運行在主線程上。

2. IntentService:該服務已經啟動了一個工作線程,你不必再自己啟動,只需把要做的事寫到 onHandleIntent,它會在子線程中處理。

三道經典面試題

  1. Service 和 Activity 的區別:
    • Activity 可與用戶交互,Service 在後台做事而無需交互。
    • Activity 退出程序後會結束,而 Service 若未顯式調用停止服務,則會持續在後台運行。
    • 最大區別:沒有服務運行的後台進程叫後台進程,有服務的叫服務進程,而系統內存回收常優先回收低優先級的後台進程。
  2. 程序已退出,為何還保留空進程?為了優化用戶體驗:下次啟動該 App 時無需重新分配進程,節約時間、提高效率,只有內存不足時才回收。
  3. Service 和線程都在後台運行,二者關係如何?Service 是四大組件之一,是一個特殊的類,可在其中另開線程;Service 本身默認運行在主線程中,並非單獨進程。

四、Service 的具體使用

1. 在 Activity 中啟動與停止 Service

// 啟動服務
Intent intent = new Intent(this, MyService.class);
startService(intent);

// 停止服務
Intent intent = new Intent(this, MyService.class);
stopService(intent);

2. 通過綁定 Service 調用服務內的方法

(Activity 關閉時 Service 也會結束)

// 綁定和解綁服務
public void bindservice(View view) {
    Intent intent = new Intent(this, MyService.class);
    myServiceConnection = new MyServiceConnection();
    bindService(intent, myServiceConnection, BIND_AUTO_CREATE);
}

public void unbindservice(View view) {
    if (myServiceConnection != null) {
        unbindService(myServiceConnection);
    }
}

public void callLocalServiceMetod(View view) {
    if (binder != null) {
        final String callParentMethod = binder.callParentMethod();
        final int count = binder.getcount();
        Toast.makeText(this, callParentMethod + count, Toast.LENGTH_SHORT).show();
    }
}

class MyServiceConnection implements ServiceConnection {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (service != null) {
            binder = (MyService.MyBinder) service;
        }
    }

    // 僅在 Service 被破壞或被殺死時調用(如系統資源不足回收服務)
    @Override
    public void onServiceDisconnected(ComponentName name) { }
}

// Service 內部
public class MyService extends Service {
    public int count;
    public boolean flag = true;

    class MyBinder extends Binder {
        public String callParentMethod() {
            return getName();
        }
        public int getcount() {
            return count;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        new Thread() {
            @Override
            public void run() {
                while (flag) {
                    count++;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        return new MyBinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        flag = false;
    }
}

3. 進程間通信(IPC / AIDL)

Android 使用接口定義語言 AIDL(Android Interface Definition Language)來暴露服務接口。實現過程:

  1. 定義服務類。
  2. 定義 AIDL 接口文件。
  3. 在服務的 onBind 方法中返回實現 AIDL 接口 Stub 的對象。
  4. 在另一個程序中調用 bindService 綁定服務。
  5. 把 AIDL 接口文件(含包名)拷貝到另一個程序中。
  6. 在 onServiceConnected 中把 IBinder 對象轉換成 AIDL 接口對象。
  7. 使用接口對象調用方法,實現進程間通信。
// AIDL 接口文件
interface MyAIDLInterface {
    String callParentMethod();
    int getcount();
}

// 服務端實現 Stub
class MyBinder2 extends MyAIDLInterface.Stub {
    @Override
    public String callParentMethod() throws RemoteException {
        return getName();
    }
    @Override
    public int getcount() throws RemoteException {
        return count;
    }
}

// 客戶端綁定並調用
class MyConnection implements ServiceConnection {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (service != null) {
            binder = MyAIDLInterface.Stub.asInterface(service);
        }
    }
    @Override
    public void onServiceDisconnected(ComponentName name) { }
}

public void bindremoteservice(View view) {
    Intent intent = new Intent();
    intent.setAction("com.ren.myservice");
    intent.setPackage("com.rgd.day16_bindservice");
    myConnection = new MyConnection();
    bindService(intent, myConnection, BIND_AUTO_CREATE);
}

透過以上方式,即可實現本地方法調用與跨進程通信兩種場景下的 Service 使用。

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