網站首頁 編程語言 正文
簡介
我們的Android在啟動一些長事務時都會使用異步,很多初學者覺得這個異步就是一個異步線程+Handler而己。如果你這么想就錯了。這一切其實靠的正是Android里的Service。
Service分成普通Service和IntentService兩種。而啟動又發為兩對:
- 第一對,startService/stopService;
- 第二對,bindService/unbindService;
后面開始我們就逐步展開對Android Service的講述,我盡量也以“保姆式教程”的方法來引領著大家循序漸進的入門,以求牢固掌握這些基礎的東西。
下面我們就來講Android中最最簡單的Service使用。
什么是Service
Service和Thread的區別。其實他們兩者并沒有太大的關系,不過有很多朋友經常把這兩個混淆了! Thread是線程,程序執行的最小單元,分配CPU的基本單位! 而Service則是Android提供一個允許長時間留駐后臺的一個組件,最常見的 用法就是做輪詢操作!或者想在后臺做一些事情,比如后臺下載更新! 記得別把這兩個概念混淆。
所以通過上面的理論我們知道,service有兩種啟動方式:
- startService/stopService
- bindService/unBindservice
我們就說startService,這個start一下去,整個service的生命周期就變得非常非常有用了。
為什么這么說呢?
因為你要寫一個service時,經常會遇到:何時給它賦初始值?何時處理?何時回調?何時結束?
這就是“生命周期”的重要性。
各位不要感到“枯燥”,就像spring boot的生命周期,當你的業務場景足夠復雜時,這種生命周期中大部分點你是需要Override到的。如果有些朋友你覺得生命周期從來沒什么用那說明你所在的項目已經足夠簡單到沒什么工作經驗、技術含量可言了,那么我奉勸你如果長時間在這么沒有含量的項目內你要考慮自身是不是會栽在35、40這個梗上了,這是很危險的一個信號。
Service的生命周期
本著保姆式教程的精神,我們說經常會使用到的Service的生命周期。各位記得,startService和bindService的啟動決定著它的生命周期也不相同。
startService和bindService的區別
服務不能自己運行。一旦Activity中調用了startService()方法啟動Service后,Activity就不能直接控制Service了。這時就需要bindService()把Activity和Service聯系起來,之后就能在Activity中指揮Service去工作了。
startService()和bindService()都能啟動Service,它們的調用順序也會對Service產生影響,具體影響我們看下去。
startService ()時Service的生命周期
通過startService(),Service會經歷 onCreate() –> onStart() 啟動Service。然后stopService()的時候直接onDestroy()。如果調用者直接退出而沒有調用stopService(),那么Service會一直在后臺運行。 注意在Service的一個生命周期之內只會調用一次onCreate()方法,stopService()之前若多次startService()則只會調用onStart()方法。
bindService()時Service的生命周期
如果打算采用bindService()方法啟動服務,在服務未被創建時,系統會先調用服務的onCreate()方法,接著調用onBind()方法。這個時候調用者和服務綁定在一起,調用者unbindService()退出了,系統就會先調用服務的onUnbind()方法,接著調用onDestroy()方法。多次調用bindService()方法并不會導致多次創建服務及綁定(也就是說onCreate()和onBind()方法并不會被多次調用)。
如果bindService()之前Service已經在運行了,那么這是調用unbindService()只會onUnbind()而不會onDestory()。
以一個例子我們先來看start/stop一個service以下它的生命周期是如何經歷的。
例子
我們的界面上就兩個按鈕,一個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方法被調用");
return null;
}
//Service被創建時調用
@Override
public void onCreate() {
Log.i(TAG, ">>>>>>onCreate方法被調用");
super.onCreate();
}
//Service被啟動時調用
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, ">>>>>>onStartCommand方法被調用");
return super.onStartCommand(intent, flags, startId);
}
//Service被關閉之前回調
@Override
public void onDestroy() {
Log.i(TAG, ">>>>>>onDestory方法被調用");
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才擁有的生命周期中。
原文鏈接:https://blog.csdn.net/lifetragedy/article/details/128174986
相關推薦
- 2022-08-15 python?datetime模塊詳解_python
- 2022-08-06 C語言詳解關鍵字sizeof與unsigned及signed的用法_C 語言
- 2023-07-16 oracle 創建存儲過程
- 2022-06-17 C#中IEnumerable接口介紹并實現自定義集合_C#教程
- 2022-10-14 composer -vvv 命令
- 2022-11-27 C++?cin不同狀態詳細講解_C 語言
- 2022-09-16 Pandas篩選DataFrame含有空值的數據行的實現_python
- 2022-07-29 Python列表append()函數使用方法詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支