Intent Service(使用Service來執行繁重的任務)

James Lin
6 min readJun 25, 2018

--

使用Service來執行繁重的任務

假設今天要做繁重的任務,那就需要開一條Thread出去執行對吧~
但是有了IntentService,就可以使用將繁重任務交由service做了。

MainActivity在addTask使用了IntentService,那是一個static方法。
由它去啟動Service執行任務(下載圖片)。

class MainActivity : AppCompatActivity() {
companion object {
public val DOWNLOAD_RESULT = "Complete"
}

private val downloadReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
if
(intent.action.equals(DOWNLOAD_RESULT)) {
var path = intent.getStringExtra(MyIntentService.EXTRA_PATH)
handleResult(path)
}
}
}
}

fun handleResult(path: String) {
var tv = textViewRoot.findViewWithTag<TextView>(path)
tv.text = path + " download success ~~ "
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
registerReceiver()
newBtn.setOnClickListener {
addTask()
}
}

fun registerReceiver() {
var filter = IntentFilter()
filter.addAction(DOWNLOAD_RESULT)
registerReceiver(downloadReceiver, filter)
}

override fun onDestroy() {
super.onDestroy()
unregisterReceiver(downloadReceiver)
}

var i = 0
fun addTask() {
var path = "http://james/imags/" + (++i) + ".jpg"
MyIntentService.startDownloadImage(this, path)
var textView = TextView(this)
textViewRoot.addView(textView)
textView.text = path + " is download ..."
textView.tag = path
}
}

Service,繁重的任務會在onHandleIntent去執行,可以由接收的intent去判斷要執行什麼任務(下載圖片)。

這邊是用Broadcast去傳送資訊給MainActivity,顯示下載完成。

class MyIntentService : IntentService("MyIntentService") {
companion object {
val SERVICE_ACTION = "DownloadImage"
val EXTRA_PATH
= "Image"
fun
startDownloadImage(context: Context, path: String) {
var i = Intent(context, MyIntentService::class.java)
i.setAction(SERVICE_ACTION)
i.putExtra(EXTRA_PATH, path)
context.startService(i)
}
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("IntentServiceId", " " + startId)
return super.onStartCommand(intent, flags, startId)
}

override fun onHandleIntent(intent: Intent?) {
intent?.let {
val
action = intent.action
if (SERVICE_ACTION.equals(action)) {
val path = intent.getStringExtra(EXTRA_PATH)
handleDownloadImage(path)
}
}
}

fun handleDownloadImage(path: String) {
try {
Thread.sleep(2000)
var i = Intent(MainActivity.DOWNLOAD_RESULT)
i.putExtra(EXTRA_PATH, path)
sendBroadcast(i)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}

override fun onCreate() {
super.onCreate()
Log.d("IntentService", " onCreate")
}

override fun onDestroy() {
super.onDestroy()
Log.d("IntentService", " onDestroy")
}
}

由此可以看出IntentService是派出一個Thread去執行任務(Task)。

任務完成後,Thread就消失了。

不管執行幾次startService,onCreate只會被執行一次,也就是說不會有同一個Service被Create多次的狀況出現。

--

--

James Lin
James Lin

No responses yet