• Android 启动service(Kotlin)


    一、使用startForegroundService()或startService()启用service

    **Activity

    1. //启动service
    2. val intent: Intent = Intent(ServiceActivity@this,MyService::class.java)
    3. //Build.VERSION_CODES.O = 26
    4. // Android8以后,不允许后台启动Service
    5. if(Build.VERSION.SDK_INT >= 26){
    6. startForegroundService(intent)
    7. }else{
    8. startService(intent)
    9. }

     **Service

    1. package com.example.buju.service
    2. import android.app.NotificationChannel
    3. import android.app.NotificationManager
    4. import android.app.Service
    5. import android.content.Context
    6. import android.content.Intent
    7. import android.graphics.BitmapFactory
    8. import android.os.Build
    9. import android.os.IBinder
    10. import android.util.Log
    11. import androidx.core.app.NotificationCompat
    12. class MyService:Service() {
    13. override fun onCreate() {
    14. super.onCreate()
    15. Log.e("MyService","onCreate")
    16. initNotification()
    17. }
    18. // 初始化通知(安卓8.0之后必须实现)
    19. private fun initNotification() {
    20. val channelName = "channelName"
    21. val channelId = "channelId"
    22. if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
    23. // 发送通知,把service置于前台
    24. val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    25. // 从Android 8.0开始,需要注册通知通道
    26. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    27. val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
    28. notificationManager.createNotificationChannel(channel)
    29. }
    30. // 页面跳转
    31. val intent = Intent(applicationContext,ServiceActivity::class.java)
    32. val pendingIntent = PendingIntent.getActivity(this, 0, intent,
    33. PendingIntent.FLAG_UPDATE_CURRENT)
    34. // 创建通知并配置相应属性
    35. val notification = NotificationCompat.Builder(this, channelId)
    36. .setSmallIcon(android.R.drawable.star_off)//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
    37. .setLargeIcon(BitmapFactory.decodeResource(getResources(), android.R.drawable.star_on))
    38. .setContentTitle("通知标题")// 标题
    39. .setContentText("通知内容")// 内容
    40. .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    41. .setContentIntent(pendingIntent)// 设置跳转
    42. .setWhen(System.currentTimeMillis())
    43. .setAutoCancel(false)
    44. .setOngoing(true)
    45. .build()
    46. // 注意第一个参数不能为0
    47. startForeground(1, notification)
    48. }
    49. }
    50. override fun onBind(intent: Intent?): IBinder? {
    51. Log.e("MyService","onBind")
    52. return null
    53. }
    54. override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    55. Log.e("MyService","onStartCommand")
    56. return super.onStartCommand(intent, flags, startId)
    57. }
    58. override fun onUnbind(intent: Intent?): Boolean {
    59. Log.e("MyService","onUnbind")
    60. return super.onUnbind(intent)
    61. }
    62. override fun onDestroy() {
    63. super.onDestroy()
    64. Log.e("MyService","onDestroy")
    65. //停止的时候销毁前台服务。
    66. stopForeground(true);
    67. }
    68. }

    注意该方法不会调用onBind()和onUnbind()

    二、绑定启用service

    **Activity

    1. package com.example.buju
    2. import android.content.ComponentName
    3. import android.content.Context
    4. import android.content.Intent
    5. import android.content.ServiceConnection
    6. import android.os.Bundle
    7. import android.os.IBinder
    8. import android.util.Log
    9. import android.view.View
    10. import android.widget.Button
    11. import androidx.appcompat.app.AppCompatActivity
    12. import com.example.buju.service.MyService
    13. class ServiceActivity:AppCompatActivity() {
    14. private var myBinder:MyService.MyBinder? = null
    15. lateinit var startBtn:Button
    16. lateinit var stopBtn:Button
    17. lateinit var getBtn:Button
    18. override fun onCreate(savedInstanceState: Bundle?) {
    19. super.onCreate(savedInstanceState)
    20. setContentView(R.layout.activity_service)
    21. initControls()
    22. }
    23. /**
    24. * 控件初始化
    25. * */
    26. private fun initControls(){
    27. startBtn = findViewById(R.id.startBtn)
    28. startBtn.setOnClickListener(btnClick)
    29. stopBtn = findViewById(R.id.stopBtn)
    30. stopBtn.setOnClickListener(btnClick)
    31. getBtn = findViewById(R.id.getBtn)
    32. getBtn.setOnClickListener(btnClick)
    33. }
    34. /**
    35. * service 连接
    36. * */
    37. private val connection = object:ServiceConnection{
    38. //Activity与Service连接成功时回调该方法
    39. override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
    40. Log.e("MyService","---------Service 成功连接----------")
    41. myBinder = service as MyService.MyBinder
    42. }
    43. // Activity与Service断开连接时回调该方法
    44. override fun onServiceDisconnected(name: ComponentName?) {
    45. Log.e("MyService","---------Service 断开连接----------")
    46. }
    47. }
    48. /**
    49. * 点击事件
    50. * */
    51. val btnClick:(View)->Unit = {
    52. when(it.id) {
    53. R.id.startBtn -> {
    54. // 绑定service
    55. val intent: Intent = Intent(ServiceActivity@this,MyService::class.java)
    56. bindService(intent,connection,Context.BIND_AUTO_CREATE)
    57. }
    58. R.id.stopBtn ->{
    59. // 解除绑定
    60. unbindService(connection)
    61. }
    62. R.id.getBtn ->{
    63. // 获取service传递过来的数据
    64. Log.e("MyService","getCount=${myBinder?.getCount()}")
    65. }
    66. else ->{
    67. }
    68. }
    69. }
    70. override fun finish() {
    71. super.finish()
    72. overridePendingTransition(R.anim.slide_no,R.anim.slide_out_from_bottom)
    73. }
    74. override fun onDestroy() {
    75. super.onDestroy()
    76. // 解除绑定
    77. unbindService(connection)
    78. }
    79. }

    **Service

    1. package com.example.buju.service
    2. import android.app.NotificationChannel
    3. import android.app.NotificationManager
    4. import android.app.Service
    5. import android.content.Context
    6. import android.content.Intent
    7. import android.graphics.BitmapFactory
    8. import android.os.Binder
    9. import android.os.Build
    10. import android.os.IBinder
    11. import android.util.Log
    12. import androidx.core.app.NotificationCompat
    13. class MyService:Service() {
    14. /**
    15. * 用于传递参数
    16. * */
    17. private var count:Int = 0
    18. private var myBinder:MyBinder = MyBinder()
    19. inner class MyBinder: Binder(){
    20. fun getCount():Int?{
    21. return count
    22. }
    23. }
    24. override fun onCreate() {
    25. super.onCreate()
    26. Log.e("MyService","onCreate")
    27. Thread(Runnable {
    28. Thread.sleep(1000)
    29. count=100
    30. }).start()
    31. initNotification()
    32. }
    33. // 初始化通知(安卓8.0之后必须实现)
    34. private fun initNotification() {
    35. val channelName = "channelName"
    36. val channelId = "channelId"
    37. if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
    38. // 发送通知,把service置于前台
    39. val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    40. // 从Android 8.0开始,需要注册通知通道
    41. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    42. val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
    43. notificationManager.createNotificationChannel(channel)
    44. }
    45. val notification = NotificationCompat.Builder(this, channelId)
    46. .setSmallIcon(android.R.drawable.star_off)//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
    47. .setLargeIcon(BitmapFactory.decodeResource(getResources(), android.R.drawable.star_on))
    48. .setContentTitle("通知标题")// 标题
    49. .setContentText("通知内容")// 内容
    50. .setWhen(System.currentTimeMillis())
    51. .setAutoCancel(false)
    52. .setOngoing(true)
    53. .build()
    54. // 注意第一个参数不能为0
    55. startForeground(1, notification)
    56. }
    57. }
    58. override fun onBind(intent: Intent?): IBinder? {
    59. Log.e("MyService","onBind")
    60. return myBinder
    61. }
    62. override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    63. Log.e("MyService","onStartCommand")
    64. return super.onStartCommand(intent, flags, startId)
    65. }
    66. override fun onUnbind(intent: Intent?): Boolean {
    67. Log.e("MyService","onUnbind")
    68. return super.onUnbind(intent)
    69. }
    70. override fun onDestroy() {
    71. super.onDestroy()
    72. Log.e("MyService","onDestroy")
    73. //停止的时候销毁前台服务。
    74. stopForeground(true);
    75. }
    76. }

  • 相关阅读:
    Windows安装svn命令
    java计算机毕业设计基层党支部建设平台MyBatis+系统+LW文档+源码+调试部署
    MAC 版PowerPoint 插入latex数学公式
    读取Excel的工具类——ExcelKit
    javaWeb网上购物系统的设计与实现
    【WSN】无线传感器网络 X-Y 坐标到图形视图和位字符串前缀嵌入方法研究(Matlab代码实现)
    scss文件自动导入
    在建工程预转固后 预转固卡片一次性计提了折旧 后续月份又发生了价值调减的情况
    先序遍历序列+中序遍历序列构建二叉树
    Numpy基础教程
  • 原文地址:https://blog.csdn.net/qq_19688207/article/details/136739155