我的第一行Android代码-Service

本文详细介绍了Android中的Service组件,包括其生命周期、如何通过startService()和bindService()创建Service。示例代码展示了如何在Service中处理耗时任务、如何与Service交互以及Service的启动与绑定流程。
摘要由CSDN通过智能技术生成

目录

1.Service

2.Service生命周期

3.创建Service

1.Service

Service启动后默认是运行在主线程中,在执行具体耗时任务过程中要手动开启子线程

2.Service生命周期

 

3.创建Service

3.1普通启动startService()

  • 编写自己的Service且继承Service类
  • 在AndroidMainfest中注册编写的Service
  • 在需要启动的Activity中StartService启动服务
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log

class MyService : Service() {

    private val TAG = "MyService"
    //必须要实现的方法
    override fun onBind(intent: Intent): IBinder?{

        Log.e(TAG, "onBind方法被调用!")
        return null
    }

    //Service被创建时调用
    override fun onCreate() {
        Log.e(TAG, "onCreate方法被调用!")
        super.onCreate()
    }

    //Service被启动时调用
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(TAG, "onStartCommand方法被调用!")
        return super.onStartCommand(intent, flags, startId)
    }

    //Service被关闭之前回调
    override fun onDestroy() {
        Log.e(TAG, "onDestory方法被调用!")
        super.onDestroy()
    }
}

AndroidMainfest中注册Service:

<service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.i("Activity生命周期","onCreate方法调用,第一次创建时进行调用")

        val button=findViewById<View>(R.id.button2)
        button.setOnClickListener{
            val intent = Intent(this,MyService::class.java);
            startService(intent);
        }
    }
}

3.2启动bindService()

步骤同创建普通启动startService()

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log

class BinderService : Service() {
    private val TAG = "BinderService"
    private var count = 0
    private var quit = false

    private val binder: MyBinder = MyBinder()

    //创建内部类
    inner class MyBinder : Binder() {
        fun getCount(): Int {
            return count
        }
    }

    override fun onBind(intent: Intent): IBinder {
        Log.e(TAG, "onBind方法被调用!")
        return binder
    }

    //Service被创建时回调
    override fun onCreate() {
        super.onCreate()
        Log.e(TAG, "onCreate方法被调用!")
        //创建一个线程动态地修改count的值
        object : Thread() {
            override fun run() {
                while (!quit) {
                    try {
                        sleep(1000)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    count++
                }
            }
        }.start()
    }

    //Service断开连接时回调
    override fun onUnbind(intent: Intent?): Boolean {
        Log.i(TAG, "onUnbind方法被调用!")
        return true
    }

    //Service被关闭前回调
    override fun onDestroy() {
        super.onDestroy()
        quit = true
        Log.i(TAG, "onDestroyed方法被调用!")
    }

    override fun onRebind(intent: Intent?) {
        Log.i(TAG, "onRebind方法被调用!")
        super.onRebind(intent)
    }
}

AndroidMainfest中注册Service: 

 <service
            android:name=".BinderService"
            android:enabled="true"
            android:exported="true"></service>
        <service

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)
        var binder=BinderService().MyBinder()


        val conn: ServiceConnection = object : ServiceConnection {
            //Activity与Service断开连接时回调该方法
            override fun onServiceDisconnected(name: ComponentName) {
                println("------Service DisConnected-------")
            }

            //Activity与Service连接成功时回调该方法
            override fun onServiceConnected(name: ComponentName, service: IBinder) {
                println("------Service Connected-------")
                binder = service as BinderService.MyBinder
            }
        }

        // bind服务
        val intent = Intent(this,BinderService::class.java)
        bindService(intent,conn, Context.BIND_AUTO_CREATE)
        val start_service=findViewById<View>(R.id.start)
        start_service.setOnClickListener {
            // 从服务获取数据
            Log.e("BinderService","getCount:${binder?.getCount()}")
        }

        // 停止按钮
        val stop_service=findViewById<View>(R.id.stop)
        stop_service.setOnClickListener {
            unbindService(conn)
        }
    }
    }

布局文件

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止" />


    </LinearLayout>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值