Kotlin se da cuenta del uso simple del Servicio

1 método de comunicación asíncrona

Durante la ejecución de Android, todos los programas se ejecutan en el subproceso principal, por lo que cuando se utiliza el bloque de código de subprocesos para actualizar algunos componentes, se requiere un controlador de comunicación asincrónica.

override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.service_test_main)

        //实现异步通信的方式进行更新数据
        val handler=object : Handler(Looper.getMainLooper()){
    
    
            override fun handleMessage(msg: Message) {
    
    
                when(msg.what){
    
    
                    1->textView.text="师者所以传道授业解惑也"
                }
            }
        }
        //如果想在子线程里面进行组件的更新,需要使用到异步机制
        change_textView.setOnClickListener(){
    
    
            thread {
    
    
                val msg=Message()
                //更新文字
                msg.what=1
                handler.sendMessage(msg)
            }
        }
 }

Pasos a seguir: 1 Cree un objeto controlador y vuelva a escribir el método handlerMessage en él para procesar la lógica después de que llegue el mensaje. 2 Cree un objeto de mensaje y vincule la categoría del mensaje enviado para que pueda distinguir los métodos de procesamiento de diferentes lógicas. 3handler para enviar mensajes

2Inicio y parada del servicio

1 Heredar el servicio en MyService e implementar los métodos para obtener un servicio personalizado, incluidos principalmente los siguientes métodos de onBinder

//此方法用来和Activity进行通信使用
    override fun onBind(intent: Intent): IBinder {
    
    
        return mBinder
    }

    //只有第一次调用的时候才会执行
    override fun onCreate() {
    
    
        super.onCreate()
    }
    //每次启动时都会调用
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    
    
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
    
    
        super.onDestroy()
    }

Al iniciar en Actividad, es similar a la forma de iniciar Actividad

start_service.setOnClickListener(){
    
    
            val intent= Intent(this,MyService::class.java)
            startService(intent)
        }
        end_service.setOnClickListener(){
    
    
            val intent=Intent(this,MyService::class.java)
            stopService(intent)
        }

3 Espere que la Actividad y el Servicio se comuniquen, hágale saber a la Actividad qué está haciendo el Servicio o cómo está progresando. Debe usar el método onBind() en Service.

1 Herede la clase Binder() en el servicio, escriba la lógica en esta clase y devuelva el resultado a través del método onBind()


class MyService : Service() {
    
    
    //为了实现和Activity的通信,模拟开启服务来进行下载功能
    private val mBinder=DownloadBinder()
    class DownloadBinder: Binder(){
    
    
        fun startDownload(){
    
    
            Log.d("MyService","开始下载")

        }
        fun getProgress():Int{
    
    
            Log.d("MyService","当前下载的进度")
            return 20
        }
    }

    //此方法用来和Activity进行通信使用
    override fun onBind(intent: Intent): IBinder {
    
    
        return mBinder
    }

    //只有第一次调用的时候才会执行
    override fun onCreate() {
    
    
        super.onCreate()
    }
    //每次启动时都会调用
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    
    
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
    
    
        super.onDestroy()
    }

}

2. En la actividad, primero debe vincular la actividad y el servicio, primero implementar el método en la interfaz de ServiceConnection y luego realizar la operación lógica después de vincular y la operación lógica después de desvincular en el método.

class ServiceTest:AppCompatActivity() {
    
    

    lateinit var downBinder:MyService.DownloadBinder

    private val connnection=object :ServiceConnection{
    
    
        //该方法会在Activity与Service绑定之后进行调用
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
    
    
            downBinder=service as MyService.DownloadBinder
            downBinder.startDownload()
            downBinder.getProgress()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
    
    
            Log.d("serviceTest","Service和Activity解绑成功")
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.service_test_main)

        //实现异步通信的方式进行更新数据
        val handler=object : Handler(Looper.getMainLooper()){
    
    
            override fun handleMessage(msg: Message) {
    
    
                when(msg.what){
    
    
                    1->textView.text="师者所以传道授业解惑也"
                }
            }
        }
        //如果想在子线程里面进行组件的更新,需要使用到异步机制
        change_textView.setOnClickListener(){
    
    
            thread {
    
    
                val msg=Message()
                //更新文字
                msg.what=1
                handler.sendMessage(msg)
            }
        }
        //service的启动和停止
        start_service.setOnClickListener(){
    
    
            val intent= Intent(this,MyService::class.java)
            startService(intent)
        }
        end_service.setOnClickListener(){
    
    
            val intent=Intent(this,MyService::class.java)
            stopService(intent)
        }
        //数据和Service进行通信,获取到service的正在做的事情,需要对Service进行绑定
        bind_service.setOnClickListener(){
    
    
            val intent=Intent(this,MyService::class.java)
            bindService(intent,connnection, Context.BIND_AUTO_CREATE)//绑定service

        }
        unBind_service.setOnClickListener(){
    
    
            unbindService(connnection)
        }

    }

4 Realizar el Servicio en primer plano

Haga clic en el botón en la Actividad principal para iniciar el Servicio actual en la notificación de primer plano


class ForegroundServiceTest : Service() {
    
    
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate() {
    
    
        super.onCreate()
        val manager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channel=NotificationChannel("myService","前台Service通知",NotificationManager.IMPORTANCE_DEFAULT)
        manager.createNotificationChannel(channel)
        val intent=Intent(this,ServiceTest::class.java)
        val pi=PendingIntent.getActivity(this,0,intent,0)
        val notification=NotificationCompat.Builder(this,"myService")
            .setContentTitle("前台Service主题")
            .setContentText("前台的Service的内容")
            .setSmallIcon(R.drawable.ic_baseline_arrow_back_ios_24)
            .setLargeIcon(BitmapFactory.decodeResource(resources,R.drawable.ic_baseline_menu_24))
            .setContentIntent(pi)
            .build()
        startForeground(1,notification)
    }

    override fun onBind(intent: Intent): IBinder {
    
    
        TODO("Return the communication channel to the service.")
    }
}

5 Operaciones más estandarizadas al realizar tareas en Servicio

En general, es posible que sea necesario realizar operaciones que consumen mucho tiempo en el Servicio, y el subproceso principal debe obtener los resultados, pero ANR (Aplicación que no responde) ocurrirá después de mucho tiempo sin obtener los resultados, por lo que para resolver esta situación , es más estándar. El método de escritura es crear un nuevo subproceso en el Servicio para procesar la tarea y realizar un trabajo asíncrono.

 //每次启动时都会调用
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    
    
    thread{
    
    
//在里面进行逻辑的处理工作,最后别忘了进行关闭
         stopSelf()
}
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
    
    
        super.onDestroy()
    }

Supongo que te gusta

Origin blog.csdn.net/m0_56184347/article/details/129698143
Recomendado
Clasificación