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

结果

相关推荐
消失的旧时光-19431 小时前
Android USB 通信开发
android·java
吃汉堡吃到饱1 小时前
【Android】浅析View.post()
android
咕噜企业签名分发-淼淼1 小时前
开发源码搭建一码双端应用分发平台教程:逐步分析注意事项
android·ios
betazhou2 小时前
mariadb5.5.56在centos7.6环境安装
android·数据库·adb·mariadb·msyql
doublelixin7 小时前
AOSP (Android11) 集成Google GMS三件套
android
xzkyd outpaper10 小时前
onSaveInstanceState() 和 ViewModel 在数据保存能力差异
android·计算机八股
CYRUS STUDIO11 小时前
FART 脱壳某大厂 App + CodeItem 修复 dex + 反编译还原源码
android·安全·逆向·app加固·fart·脱壳
WAsbry12 小时前
现代 Android 开发自定义主题实战指南
android·kotlin·material design
xzkyd outpaper12 小时前
Android动态广播注册收发原理
android·计算机八股
唐墨12312 小时前
android与Qt类比
android·开发语言·qt