網站首頁 編程語言 正文
服務簡介
服務是Android中的四大組件之一,它能夠長期在后臺運行且不提供用戶界面。即使用戶切到另一應用程序,服務仍可以在后臺運行。
服務的創建
(1)創建Service子類
class MyService : Service() {
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
}
(2)在清單文件中配置
<service android:name=".MyService" android:enabled="true" android:exported="true"> </service>
服務的啟動方式
(1)通過startService()方法啟動
當通過startService()方法啟動服務時,需要自身調用stopSelf()方法或者其他組件調用stopService()方法時服務才能停止。
(2)通過bindService()方法啟動
當使用bingService()方法啟動服務時,需要調用unbindService()方法解除綁定之后就會被銷毀。
(3)即調用startService()方法,又調用了bingService()方法
這種情況下,要同時調用stopService()和unbindService()方法。
Service的生命周期
- onCreate():第一次創建服務時執行的方法。
- onDestory():服務被銷毀時執行的方法。
- onStartCommand():訪問者通過startService(intent)啟動,服務時執行的方法。
- onBind():使用bindService()方式啟動服務調用的方法。
- onUnbind():解除綁定時調用的方法。
Activity和Service進行通信
Activity和Service之間的通信由IBinder負責,在Activity中,創建一個類實現ServiceConnection接口,并且在這個類中重寫onServiceConnected方法(當Service被綁定時會回調這個方法)和onServiceDisconnected方法(Service的創建進程崩潰或者被殺掉才會調用),然后再綁定Service。
class MainActivity : AppCompatActivity() {
lateinit var myBinder:MyService.mBinder
private val connection=object :ServiceConnection{
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
myBinder=p1 as MyService.mBinder
myBinder.a()
}
override fun onServiceDisconnected(p0: ComponentName?) {
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bindbutton:Button=findViewById(R.id.bindbutton)
val unbindbutton:Button=findViewById(R.id.unbindbutton)
bindbutton.setOnClickListener {
val intent=Intent(this,MyService::class.java)
bindService(intent,connection,Context.BIND_AUTO_CREATE)//綁定Service
}
unbindbutton.setOnClickListener {
unbindService(connection)//解綁Service
}
}
}
在Service中,需要創建一個類繼承Binder,在onBind()方法中返回這個類的實例。
class MyService : Service() {
private val myBinder=mBinder()
class mBinder:Binder(){
fun a(){
Log.d("data","service")
}
}
override fun onBind(intent: Intent): IBinder {
return myBinder
}
override fun onCreate() {
super.onCreate()
Log.d("data","onCreate")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("data","onStartCommand")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
Log.d("data","onDestroy")
}
}
實現前臺Service
前臺服務執行一些用戶能注意到的操作。
代碼如下:
需要先進行權限聲明
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
class MyService : Service() {
private val myBinder=mBinder()
class mBinder:Binder(){
fun a(){
Log.d("data","service")
}
}
override fun onBind(intent: Intent): IBinder {
return myBinder
}
override fun onCreate() {
super.onCreate()
Log.d("data","onCreate")
val manager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
val channel=NotificationChannel("my_service","前臺Service通知",NotificationManager.IMPORTANCE_DEFAULT)
manager.createNotificationChannel(channel)
}
val intent=Intent(this,MainActivity::class.java)
val pi=PendingIntent.getActivity(this,0,intent,0)
val notification=NotificationCompat.Builder(this,"my_service")
.setContentTitle("這是主題")
.setContentText("這是內容")
.setSmallIcon(R.drawable.ic_baseline_favorite_border_24)
.build()
startForeground(1,notification)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("data","onStartCommand")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
Log.d("data","onDestroy")
}
}
原文鏈接:https://blog.csdn.net/weixin_63357306/article/details/128016900
相關推薦
- 2023-05-21 numpy.unique()使用方法_python
- 2022-04-05 python將列表轉換為字符串(含有引號,用逗號間隔)
- 2022-04-23 window.open打開新窗口設置顯示位置及大小
- 2022-07-11 搭建spring MVC框架,完成和servlet相似的操作
- 2022-08-30 啟動Activity但是不顯示界面
- 2022-03-09 c++中STL庫隊列詳細介紹_C 語言
- 2022-06-02 C語言實現簡單的抽獎系統_C 語言
- 2022-10-13 Python變量教程之全局變量和局部變量_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同步修改后的遠程分支