注:这只是个Demo
以下载为案例,实现开启下载,暂停下载,下载进度不断发送给activity
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)
}
}
}
在清单文件配置
<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>
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()
}
}
结果