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()
    }
}

结果

相关推荐
丁大黄3 小时前
【Android】Android 服务保活/常驻
android
少说多做3434 小时前
Android 单选框RadioGroup+RadioButton
android
guoruijun_2012_44 小时前
安卓 获取 喇叭 听筒 音频输出流 AudioPlaybackCapture API 可以捕获音频输出流
android·音视频
昊虹AI笔记5 小时前
PHP中类名加双冒号的作用
android·java·php
ShanLiang_Build6 小时前
Android 使用Charles抓包显示Unknown
android
逃课的小学生6 小时前
android 安全sdk相关
android
今人不见古时月,今月曾经照古人6 小时前
android studio Terminal控制台命令打包 apk
android·ide·android studio
Winston Wood7 小时前
Android 图形系统之一:概览
android·图形系统
柯南二号7 小时前
Android 实现双列图片瀑布流式布局
android·recycleview·瀑布流
manok7 小时前
Android - 权限管理漏洞
android·sast·静态分析规则