Android入門之Service的使用詳解
簡介
我們的Android在啟動一些長事務(wù)時都會使用異步,很多初學者覺得這個異步就是一個異步線程+Handler而己。如果你這么想就錯了。這一切其實靠的正是Android里的Service。
Service分成普通Service和IntentService兩種。而啟動又發(fā)為兩對:
- 第一對,startService/stopService;
- 第二對,bindService/unbindService;
后面開始我們就逐步展開對Android Service的講述,我盡量也以“保姆式教程”的方法來引領(lǐng)著大家循序漸進的入門,以求牢固掌握這些基礎(chǔ)的東西。
下面我們就來講Android中最最簡單的Service使用。
什么是Service
Service和Thread的區(qū)別。其實他們兩者并沒有太大的關(guān)系,不過有很多朋友經(jīng)常把這兩個混淆了! Thread是線程,程序執(zhí)行的最小單元,分配CPU的基本單位! 而Service則是Android提供一個允許長時間留駐后臺的一個組件,最常見的 用法就是做輪詢操作!或者想在后臺做一些事情,比如后臺下載更新! 記得別把這兩個概念混淆。

所以通過上面的理論我們知道,service有兩種啟動方式:
- startService/stopService
- bindService/unBindservice
我們就說startService,這個start一下去,整個service的生命周期就變得非常非常有用了。
為什么這么說呢?
因為你要寫一個service時,經(jīng)常會遇到:何時給它賦初始值?何時處理?何時回調(diào)?何時結(jié)束?
這就是“生命周期”的重要性。
各位不要感到“枯燥”,就像spring boot的生命周期,當你的業(yè)務(wù)場景足夠復雜時,這種生命周期中大部分點你是需要Override到的。如果有些朋友你覺得生命周期從來沒什么用那說明你所在的項目已經(jīng)足夠簡單到?jīng)]什么工作經(jīng)驗、技術(shù)含量可言了,那么我奉勸你如果長時間在這么沒有含量的項目內(nèi)你要考慮自身是不是會栽在35、40這個梗上了,這是很危險的一個信號。
Service的生命周期
本著保姆式教程的精神,我們說經(jīng)常會使用到的Service的生命周期。各位記得,startService和bindService的啟動決定著它的生命周期也不相同。
startService和bindService的區(qū)別
服務(wù)不能自己運行。一旦Activity中調(diào)用了startService()方法啟動Service后,Activity就不能直接控制Service了。這時就需要bindService()把Activity和Service聯(lián)系起來,之后就能在Activity中指揮Service去工作了。
startService()和bindService()都能啟動Service,它們的調(diào)用順序也會對Service產(chǎn)生影響,具體影響我們看下去。
startService ()時Service的生命周期
通過startService(),Service會經(jīng)歷 onCreate() –> onStart() 啟動Service。然后stopService()的時候直接onDestroy()。如果調(diào)用者直接退出而沒有調(diào)用stopService(),那么Service會一直在后臺運行。 注意在Service的一個生命周期之內(nèi)只會調(diào)用一次onCreate()方法,stopService()之前若多次startService()則只會調(diào)用onStart()方法。
bindService()時Service的生命周期
如果打算采用bindService()方法啟動服務(wù),在服務(wù)未被創(chuàng)建時,系統(tǒng)會先調(diào)用服務(wù)的onCreate()方法,接著調(diào)用onBind()方法。這個時候調(diào)用者和服務(wù)綁定在一起,調(diào)用者unbindService()退出了,系統(tǒng)就會先調(diào)用服務(wù)的onUnbind()方法,接著調(diào)用onDestroy()方法。多次調(diào)用bindService()方法并不會導致多次創(chuàng)建服務(wù)及綁定(也就是說onCreate()和onBind()方法并不會被多次調(diào)用)。
如果bindService()之前Service已經(jīng)在運行了,那么這是調(diào)用unbindService()只會onUnbind()而不會onDestory()。
以一個例子我們先來看start/stop一個service以下它的生命周期是如何經(jīng)歷的。
例子

我們的界面上就兩個按鈕,一個startService,一個stopService。
來看具體的代碼
全代碼
后端代碼
service類-SimpleService類
package org.mk.android.demoandroidsimpleservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class SimpleService extends Service {
private final String TAG = "SimpleService";
public SimpleService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.i(TAG, ">>>>>>onBind方法被調(diào)用");
return null;
}
//Service被創(chuàng)建時調(diào)用
@Override
public void onCreate() {
Log.i(TAG, ">>>>>>onCreate方法被調(diào)用");
super.onCreate();
}
//Service被啟動時調(diào)用
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, ">>>>>>onStartCommand方法被調(diào)用");
return super.onStartCommand(intent, flags, startId);
}
//Service被關(guān)閉之前回調(diào)
@Override
public void onDestroy() {
Log.i(TAG, ">>>>>>onDestory方法被調(diào)用");
super.onDestroy();
}
}
運行主類
package org.mk.android.demoandroidsimpleservice;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button buttonStartSimpleService;
private Button buttonStopSimpleService;
private Intent intent = new Intent();
private Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = MainActivity.this;
buttonStartSimpleService = (Button) findViewById(R.id.buttonStartSimpleService);
buttonStopSimpleService = (Button) findViewById(R.id.buttonStopSimpleService);
buttonStartSimpleService.setOnClickListener(new OnClickListener());
buttonStopSimpleService.setOnClickListener(new OnClickListener());
}
class OnClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
Intent eIntent;
switch (view.getId()) {
case R.id.buttonStartSimpleService:
intent=new Intent(ctx,SimpleService.class);
startService(intent);
break;
case R.id.buttonStopSimpleService:
intent=new Intent(ctx,SimpleService.class);
stopService(intent);
break;
}
}
}
}
為了運行Service你還需要在AndroidManifest.xml文件中注冊這個Service
注意下文中的<service>塊。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.DemoAndroidSimpleService"
tools:targetApi="31">
<service
android:name=".SimpleService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action
android:name="org.mk.android.demoandroidsimpleservice.SimpleService"/>
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>
運行后的效果

這個運行后的效果恰恰說明了一個這樣的效果:通過startService啟動的Service的生命周期不會觸碰到那些bindService才擁有的生命周期中。
到此這篇關(guān)于Android入門之Service的使用詳解的文章就介紹到這了,更多相關(guān)Android Service內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Android?NotificationListenerService通知監(jiān)聽服務(wù)使用
- Android Google AutoService框架使用詳解
- Android使用Service實現(xiàn)IPC通信的2種方式
- 說說在Android如何使用服務(wù)(Service)的方法
- Android使用Service實現(xiàn)簡單音樂播放實例
- 淺談Android中Service的注冊方式及使用
- Android編程使用Service實現(xiàn)Notification定時發(fā)送功能示例
- Android 通知使用權(quán)(NotificationListenerService)的使用
- Android Service功能使用示例代碼
相關(guān)文章
Android 中ScrollView與ListView沖突問題的解決辦法
這篇文章主要介紹了Android 中ScrollView與ListView沖突問題的解決辦法的相關(guān)資料,希望通過本文能幫助到大家,讓大家掌握解決問題的辦法,需要的朋友可以參考下2017-10-10
flutter InkWell實現(xiàn)水波紋點擊效果
這篇文章主要為大家詳細介紹了flutter InkWell實現(xiàn)水波紋點擊效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
android MediaRecorder實現(xiàn)錄屏時帶錄音功能
這篇文章主要介紹了android MediaRecorder錄屏時帶錄音功能實現(xiàn)代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04

