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

结果

相关推荐
Devil枫33 分钟前
Kotlin高级特性深度解析
android·开发语言·kotlin
ChinaDragonDreamer35 分钟前
Kotlin:2.1.20 的新特性
android·开发语言·kotlin
雨白11 小时前
Jetpack系列(二):Lifecycle与LiveData结合,打造响应式UI
android·android jetpack
kk爱闹13 小时前
【挑战14天学完python和pytorch】- day01
android·pytorch·python
每次的天空14 小时前
Android-自定义View的实战学习总结
android·学习·kotlin·音视频
恋猫de小郭15 小时前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
断剑重铸之日16 小时前
Android自定义相机开发(类似OCR扫描相机)
android
随心最为安16 小时前
Android Library Maven 发布完整流程指南
android
岁月玲珑16 小时前
【使用Android Studio调试手机app时候手机老掉线问题】
android·ide·android studio
还鮟20 小时前
CTF Web的数组巧用
android