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

结果

相关推荐
雨白1 小时前
Jetpack系列(二):Lifecycle与LiveData结合,打造响应式UI
android·android jetpack
kk爱闹3 小时前
【挑战14天学完python和pytorch】- day01
android·pytorch·python
每次的天空4 小时前
Android-自定义View的实战学习总结
android·学习·kotlin·音视频
恋猫de小郭5 小时前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
断剑重铸之日6 小时前
Android自定义相机开发(类似OCR扫描相机)
android
随心最为安6 小时前
Android Library Maven 发布完整流程指南
android
岁月玲珑6 小时前
【使用Android Studio调试手机app时候手机老掉线问题】
android·ide·android studio
还鮟10 小时前
CTF Web的数组巧用
android
小蜜蜂嗡嗡12 小时前
Android Studio flutter项目运行、打包时间太长
android·flutter·android studio
aqi0012 小时前
FFmpeg开发笔记(七十一)使用国产的QPlayer2实现双播放器观看视频
android·ffmpeg·音视频·流媒体