處理異步請(qǐng)求 實(shí)現(xiàn)多線程
1.使用場(chǎng)景
線程任務(wù) 需按順序 在后臺(tái)執(zhí)行
最常見(jiàn)的場(chǎng)景:離線下載
不符合多個(gè)數(shù)據(jù)同時(shí)請(qǐng)求的場(chǎng)景:所有的任務(wù)都在同一個(gè)Thread looper里執(zhí)行
2.使用步驟
1.定義IntentService的子類(lèi) 復(fù)寫(xiě)onHandleIntent() 方法
class myIntentService extends IntentService {
public myIntentService() {
super("myIntentService");
}
//根據(jù)Intent實(shí)現(xiàn)耗時(shí)操作
@Override
protected void onHandleIntent(@Nullable Intent intent) {
String taskName = intent.getExtras().getString("taskName");
switch (taskName) {
case "task1":
Log.d("myIntentService","do task1");
break;
case "task2":
Log.d("myIntentService","do task2");
break;
default:
break;
}
}
@Override
public void onCreate() {
super.onCreate();
}
//重寫(xiě)onStartCommand() 方法
//默認(rèn)實(shí)現(xiàn) = 將請(qǐng)求的Intent添加到工作隊(duì)列
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
2.在Manifest.xml中注冊(cè)服務(wù)
<service android:name=".myIntentService" >
<intent-filter>
<action android:name="cm.sc.ff" />
</intent-filter>
</service>
3.在Activity中開(kāi)啟service服務(wù)
void startService () {
//同一個(gè)服務(wù)只會(huì)開(kāi)啟1個(gè)工作線程
Intent i = new Intent("cn.scu.finch");
Bundle bundle = new Bundle();
bundle.putString("taskName","task1");
i.putExtras(bundle);
startService(i);
Intent i2 = new Intent("cn.scu.finch");
Bundle bundle2 = new Bundle();
bundle2.putString("taskName","task2");
i2.putExtras(bundle2);
startService(i2);
}
3.對(duì)比
3.1 與Service的區(qū)別
image.png
3.2 與其他線程的區(qū)別
image.png