package com.example.servicedemoimport android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Handlerimport android.os.Messageimport android.os.Messengerimport android.view.Viewimport android.widget.Buttonimport android.widget.ProgressBarimport java.lang.ref.WeakReferenceclass MainActivity2 : AppCompatActivity(), View.OnClickListener { lateinit var intent2: Intent var progressBar: ProgressBar?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) progressBar =findViewById(R.id.progressbar) var btn_start_service: Button? = null var btn_stop_service: Button? = null btn_start_service = findViewById(R.id.btn_start_service) btn_stop_service = findViewById(R.id.btn_stop_service) btn_stop_service?.setOnClickListener(this) btn_start_service?.setOnClickListener(this) } override fun onClick(v: View?) { when (v?.id) { R.id.btn_start_service -> { // val intent = Intent() intent.setClass(this, MyIntentService::class.java) intent.action = MyIntentService.DOWNLOAD_ACTION_KEY intent.putExtra(MyIntentService.TEST_AUTHOR_KEY, "Jere") //将 Messenger 传递给 IntentService, 使其传递消息回来,实现客户端与服务端之间进行沟通 intent.putExtra(MyIntentService.TEST_MESSENGER_KEY, Messenger(MessengerHandler(this))) startService(intent) } R.id.btn_stop_service -> { stopService(intent) } } } class MessengerHandler(activity: MainActivity2) : Handler() { var weakReference: WeakReference<MainActivity2> = WeakReference(activity) override fun handleMessage(msg: Message) { super.handleMessage(msg) //msg 为 IntentService 回复的消息,包含 Bundle 等信息。 val bundle: Bundle = msg.data //获取 IntentService 传递过来的 下载进度 参数 val downloadProgressBarValue: Int = bundle.get(MyIntentService.DOWNLOAD_PROGRESS_BAR_VALUE_KEY) as Int val activity: MainActivity2? = weakReference.get() //将下载进度设置成 ProgressBar 的进度,显示出来。 if (activity != null && !activity.isFinishing) { activity.progressBar?.progress=downloadProgressBarValue } } }}
评论