說說在Android如何使用服務(Service)的方法
Android 服務(Service)適合執(zhí)行那些不需要和用戶交互而且還要求長期運行的任務。
服務的運行不依賴于任何用戶界面,即使 APP 被切換到后臺,或者打開了另外一個 APP,服務仍然能夠保持正常運行。
但是當某個 APP 進程被殺掉時,那么這個 APP 所創(chuàng)建的所有服務也就停止咯。
另外,服務本身并不會自動開啟線程,服務代碼默認是運行在主線程中的。所以如果需要執(zhí)行的業(yè)務邏輯耗時長,那么為了防止主線程被阻塞,我們必須在服務內部創(chuàng)建子線程來執(zhí)行這些業(yè)務邏輯。
1 定義服務
在 Android Studio 中可以通過 File→New→Service→Service 來創(chuàng)建服務:

在彈出的對話框中配置服務:

在此配置服務名。下面兩個配置項說明如下:
* Exported:是否允許除了當前程序之外的其他程序訪問這個服務。(默認勾選)
* Enabled:是否啟用這個服務 。 (默認勾選)
public class FirstService extends Service {
private static final String TAG = "FirstService";
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
public FirstService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
創(chuàng)建好后的服務繼承自 Service,并且需要實現(xiàn) onBind() 方法。我們在此還重寫了以下幾個方法:
| 方法 | 說明 |
|---|---|
| void onCreate() | 服務創(chuàng)建時調用該方法。 |
| onStartCommand(Intent intent, int flags, int startId) | 每次服務啟動時調用該方法。 |
| void onDestroy() | 服務銷毀時調用該方法。 |
我們還在這些方法中加入了日志,便于觀察運行結果。
此外,在此類的任何位置調用 stopSelf() 方法,服務就會自行停止。
定義好服務后,需要在 AndroidManifest.xml 中注冊服務(如果用的是 Android Studio,那么這一步它已經(jīng)幫我們做啦):
<service android:name=".FirstService" android:enabled="true" android:exported="true"></service>
2 啟動或停止服務
借助 Intent,我們就可以控制服務的啟動與停止啦O(∩_∩)O哈哈~
final Context context = this;
findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//啟動服務
startService(new Intent(context, FirstService.class));
}
});
findViewById(R.id.stop_service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//停止服務
stopService(new Intent(context, FirstService.class));
}
});
這里的 startService() 和 stopService() 方法都是定義在 Context 類中,所以在活動類中可以直接調用。
執(zhí)行結果:
D/FirstService: onCreate D/FirstService: onStartCommand D/FirstService: onDestroy
**注意:**onCreate() 在第一次創(chuàng)建服務時被調用,而 onStartCommand() 會在每次啟動服務時被調用。
服務啟動后,可以在 Android 的 Settings → Developer opinions → Running services 中發(fā)現(xiàn)它:

點擊 APP 后,可以看到服務詳情:

如果找不到 Developer opinions 選項,請先在 Android 的 Settings → About emulated device → 多次點擊 Build number 就可以開啟開發(fā)者模式啦:

3 活動控制服務
活動是通過實現(xiàn) ServiceConnection 接口來與服務建立連接的,它包含以下兩個方法:
| 方法 | 說明 |
|---|---|
| onServiceConnected(ComponentName name, IBinder service) | 服務綁定后調用該方法。 |
| onServiceDisconnected(ComponentName name) | 服務解綁后調用該方法。 |
而服務是通過實現(xiàn) IBinder onBind(Intent intent) 方法來轉換為 onServiceConnected() 方法所需要的 IBinder 型的 service 參數(shù)的。
首先,我們修改服務類:
public class FirstService extends Service {
class CustomBinder extends Binder {
public void init(){
Log.d(TAG, "init CustomBinder");
}
}
@Override
public IBinder onBind(Intent intent) {
return new CustomBinder();
}
}
這里,我們定義了一個內部類 CustomBinder,里面實現(xiàn)了一個簡單的初始化方法。然后在 onBind() 方法中返回它的實例。
接著,我們修改活動類,創(chuàng)建 ServiceConnection 實例:
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "onServiceConnected");
FirstService.CustomBinder customBinder = (FirstService.CustomBinder) service;
customBinder.init();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "onServiceDisconnected");
}
};
現(xiàn)在,就可以通過 ServiceConnection 實例來綁定或者解綁服務啦。
綁定服務:
bindService 接收三個參數(shù):
| 參數(shù) | 類型 | 說明 |
|---|---|---|
| service | Intent | 這個 Intent 將綁定當前的活動類與服務類。 |
| conn | ServiceConnection | ServiceConnection 對象。 |
| flags | int | 綁定服務的方式。這里的 BIND_AUTO_CREATE 表示綁定后自動創(chuàng)建服務。 |
【綁定服務】輸出結果:
D/FirstService: onCreate D/MainActivity: onServiceConnected D/FirstService: init CustomBinder
解綁服務:
unbindService(connection);
只要傳入 ServiceConnection 對象即可解綁,是不是很簡單呀 O(∩_∩)O哈哈~
【解綁服務】輸出結果:
D/FirstService: onDestroy
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Android入門之Service的使用詳解
- Android?NotificationListenerService通知監(jiān)聽服務使用
- Android Google AutoService框架使用詳解
- Android使用Service實現(xiàn)IPC通信的2種方式
- Android使用Service實現(xiàn)簡單音樂播放實例
- 淺談Android中Service的注冊方式及使用
- Android編程使用Service實現(xiàn)Notification定時發(fā)送功能示例
- Android 通知使用權(NotificationListenerService)的使用
- Android Service功能使用示例代碼
相關文章
詳談android 6.0 fuse文件系統(tǒng)的掛載和卸載問題
今天小編就為大家分享一篇詳談android 6.0 fuse文件系統(tǒng)的掛載和卸載問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Android GSYVideoPlayer視頻播放器功能的實現(xiàn)
這篇文章主要介紹了Android GSYVideoPlayer視頻播放器功能的實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
Android EditText限制輸入字數(shù)的方法
這篇文章主要介紹了Android EditText限制輸入字數(shù)的方法,涉及Android針對EditText文本與字符串操作相關技巧,需要的朋友可以參考下2016-01-01
Android App開發(fā)中RecyclerView控件的基本使用教程
這篇文章主要介紹了Android App開發(fā)中RecyclerView控件的基本使用教程,RecyclerView在Android 5.0之后伴隨著Material Design出現(xiàn),管理布局方面十分強大,需要的朋友可以參考下2016-04-04

