android Service 与 activity 通信 并不断传数据

注:这只是个Demo

以下载为案例,实现开启下载,暂停下载,下载进度不断发送给activity

Kotlin 复制代码
class DownloadService : Service() {

    override fun onBind(intent: Intent?): IBinder? {
         return MyBinder()
    }


   inner class MyBinder : Binder(){
        val service:DownloadService
            get() = this@DownloadService
    }
 
    private var mCurrentProgress:Int = 0
   
    var isStart = AtomicBoolean() 
    fun startDownload(progress:(progress:Int)-> Unit){

        if (!isStart.get()){
            Log.d("downloadService","进度:开启")
            isStart.set(true)

            Thread(object :Runnable{
                override fun run() {
                    while (isStart.get()) {
                        try { 
                            if (mCurrentProgress<100){
                                mCurrentProgress ++
                            }

                            if (mCurrentProgress>=100){
                                isStart.set(false)
                            }

                            progress.invoke(mCurrentProgress) 
                            Thread.sleep(1000)
                        } catch (e: InterruptedException) {
                            throw RuntimeException(e)
                        }
                    }
                }
            } ).start() 
        } 
    }

    fun stopDownload(){
        if (isStart.get()){
            Log.d("downloadService","进度:暂停")
            isStart.set(false)
        }
    }
 
}
Kotlin 复制代码
在清单文件配置

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application >
        
        <service android:name=".activity.DownloadService"/>

    </application>

</manifest>
Kotlin 复制代码
class DownloadActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_download)

        findViewById<View>(R.id.btnStart).setOnClickListener {
            startDownload()
        }

        findViewById<View>(R.id.btnStop).setOnClickListener {
            stopDownload()
        }

    }

    var isStartService = AtomicBoolean()
    fun startDownload(){
         if (!isStartService.get()){
             isStartService.set(true)
             Intent(this@DownloadActivity,DownloadService::class.java).apply {
                    this.putExtra("data1","数据1")
             }.let {
                 bindService(it,serviceConnection,Context.BIND_AUTO_CREATE)
             }
         }else{
             downloadService?.startDownload {progress->
                 Log.d("downloadService","++ 进度:${progress}%")
             }
         }
    }

    fun stopDownload(){
        downloadService?.stopDownload()
    }

    var downloadService:DownloadService? = null
    var serviceConnection = object :ServiceConnection{
        override fun onServiceConnected(p0: ComponentName?, iBinder: IBinder?) {

            downloadService =  (iBinder as DownloadService.MyBinder).service
            downloadService?.startDownload {progress->
                Log.d("downloadService","进度:${progress}%")
            }
        }

        override fun onServiceDisconnected(p0: ComponentName?) {
        }
    }

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

结果

相关推荐
进击的cc2 小时前
面试官:Handler 没消息时为啥不卡死?带你从源码到底层内核彻底整明白!
android·面试
Yang-Never2 小时前
OpenGL ES ->YUV图像基础知识
android·java·开发语言·kotlin·android studio
2501_915921433 小时前
常用iOS性能测试工具大全及使用指南
android·测试工具·ios·小程序·uni-app·cocoa·iphone
晨尘光3 小时前
【Android下载gradle超时解决方法】
android
zhen_hong3 小时前
ReactAgent原理
android·java·javascript
皮皮宋吖3 小时前
皮皮宋渗透日记 11|文件包含漏洞全解析:LFI/RFI/ 伪协议 / 绕过 / 防御
android·安全
阿拉斯攀登3 小时前
【无人售货柜・RK+YOLO】篇 6:安卓端落地!RK3576 + 安卓系统,YOLO RKNN 模型实时推理保姆级教程
android·人工智能·yolo·目标跟踪·瑞芯微·嵌入式驱动
只能是遇见3 小时前
ERROR 1524 (HY000) Plugin ‘mysql_native_password‘ is not loaded
android·数据库·mysql
helloworddm4 小时前
第一篇:设计模式在 Android 视频播放器中的实战应用
android·设计模式·音视频
恋猫de小郭4 小时前
Android 禁止侧载将正式实施,需要等待 24 小时冷静期
android·flutter·harmonyos