如果沒興趣的可以直接看實(shí)例。
首先把 原文 搬過來:IntentService是Service類的子類,用來處理異步請(qǐng)求』蔽恚客戶端可以通過startService(Intent)方法傳遞請(qǐng)求給IntentService,IntentService通過worker thread處理每個(gè)Intent對(duì)象幅狮,執(zhí)行完一個(gè)Intent請(qǐng)求對(duì)象所對(duì)應(yīng)的工作之后募强,如果沒有新的Intent請(qǐng)求達(dá)到株灸,則自動(dòng)停止Service;否則執(zhí)行下一個(gè)Intent請(qǐng)求所對(duì)應(yīng)的任務(wù)擎值,執(zhí)行完所有的工作之后自動(dòng)停止Service慌烧。
IntentService在處理事務(wù)時(shí),還是采用的Handler方式鸠儿,創(chuàng)建一個(gè)名叫ServiceHandler的內(nèi)部Handler屹蚊,并把它直接綁定到HandlerThread所對(duì)應(yīng)的子線程。 ServiceHandler把處理一個(gè)intent所對(duì)應(yīng)的事務(wù)都封裝到叫做onHandleIntent的虛函數(shù)进每;因此我們直接實(shí)現(xiàn)虛函數(shù)onHandleIntent汹粤,再在里面根據(jù)Intent的不同進(jìn)行不同的事務(wù)處理就可以了。
說明:worker thread處理所有通過傳遞過來的請(qǐng)求田晚,創(chuàng)建一個(gè)worker queue嘱兼,一次只傳遞一個(gè)intent到onHandleIntent中,從而不必?fù)?dān)心多線程帶來的問題贤徒。處理完畢之后自動(dòng)調(diào)用stopSelf()方法芹壕;默認(rèn)實(shí)現(xiàn)了Onbind()方法,返回值為null接奈;
模式實(shí)現(xiàn)了onStartCommand()方法踢涌,這個(gè)方法會(huì)放到worker queue中,然后在onHandleIntent()中執(zhí)行0序宦。
使用IntentService需要兩個(gè)步驟:
1睁壁、寫構(gòu)造函數(shù)
2、復(fù)寫onHandleIntent()方法(根據(jù)Intent的不同進(jìn)行不同的事務(wù)處理)
注意:IntentService的構(gòu)造函數(shù)一定是參數(shù)為空的構(gòu)造函數(shù)挨厚,然后再在其中調(diào)用super("classname")這種形式的構(gòu)造函數(shù)。
因?yàn)镾ervice的實(shí)例化是系統(tǒng)來完成的糠惫,而且系統(tǒng)是用參數(shù)為空的構(gòu)造函數(shù)來實(shí)例化Service的
---------------------以上是一些介紹和個(gè)人------------------------
寫一個(gè)Demo來模擬兩個(gè)耗時(shí)操作 Operation1與Operation2疫剃,
執(zhí)行完一個(gè)Intent請(qǐng)求對(duì)象所對(duì)應(yīng)的工作之后,如果沒有新的Intent請(qǐng)求達(dá)到硼讽,則自動(dòng)停止Service巢价;否則執(zhí)行下一個(gè)Intent請(qǐng)求所對(duì)應(yīng)的任務(wù),執(zhí)行完所有的工作之后自 動(dòng)停止Service固阁。
看是不是先執(zhí)行1壤躲,2必須等1執(zhí)行完才能執(zhí)行:
public class UploadImgService extends IntentService {
public UploadImgService() {
//必須實(shí)現(xiàn)父類的構(gòu)造方法
super("UploadImgService");
}
@Override
public IBinder onBind(Intent intent) {
System.out.println("onBind");
return super.onBind(intent);
}
@Override
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
System.out.println("onStart");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void setIntentRedelivery(boolean enabled) {
super.setIntentRedelivery(enabled);
System.out.println("setIntentRedelivery");
}
@Override
protected void onHandleIntent(Intent intent) {
//Intent是從Activity發(fā)過來的,攜帶識(shí)別參數(shù)备燃,根據(jù)參數(shù)不同執(zhí)行不同的任務(wù)
String action = intent.getExtras().getString("param");
if (action.equals("oper1")) {
System.out.println("Operation1");
}else if (action.equals("oper2")) {
System.out.println("Operation2");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
System.out.println("onDestroy");
super.onDestroy();
}
}
把生命周期方法全打印出來了碉克,待會(huì)我們來看看它執(zhí)行的過程是怎樣的。接下來是Activity并齐,在Activity中來啟動(dòng)IntentService:
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//可以啟動(dòng)多次漏麦,每啟動(dòng)一次客税,就會(huì)新建一個(gè)work thread,但I(xiàn)ntentService的實(shí)例始終只有一個(gè)
//Operation 1
Intent startServiceIntent = new Intent(this,UploadImgService.class);
Bundle bundle = new Bundle();
bundle.putString("param", "oper1");
startServiceIntent.putExtras(bundle);
startService(startServiceIntent);
//Operation 2
Intent startServiceIntent2 = new Intent(this,UploadImgService.class);
Bundle bundle2 = new Bundle();
bundle2.putString("param", "oper2");
startServiceIntent2.putExtras(bundle2);
startService(startServiceIntent2);
}
}
別急著運(yùn)行看效果撕贞,還有配置Service更耻,因?yàn)樗^承于Service,所以捏膨,它還是一個(gè)Service秧均,一定要配置,否則是不起作用的
<service android:name="com.naplec.service.UploadImgService"></service>
自己看下打印的就應(yīng)該差不多明白了
以上呢是IntentService用法号涯,現(xiàn)在我們進(jìn)入正題目胡,用IntentService上傳圖片。直接貼代碼诚隙,不明白可以問
public class UploadImgService extends IntentService {
private static final String ACTION_UPLOAD_IMG = "com.naplec.action.UPLOAD_IMAGE";
public static final String EXTRA_IMG_PATH = "com.naplec.service.IMG_PATH";
public static final String EXTRA_IMG_PARAMS = "com.naplec.service.IMG_PARAMS";
public static final String BACK_RESULT = "com.naplec.service.BACK_RESULT";
public static void startUploadImg(Context context, ArrayList<String> isList, HashMap<String, String> data) {
Intent intent = new Intent(context, UploadImgService.class);
intent.setAction(ACTION_UPLOAD_IMG);
intent.putExtra(EXTRA_IMG_PATH, isList);
intent.putExtra(EXTRA_IMG_PARAMS, data);
context.startService(intent);
}
public UploadImgService() {
super("UploadImgService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_UPLOAD_IMG.equals(action)) {
List<String> isList = (List<String>) intent.getSerializableExtra(EXTRA_IMG_PATH);
Map<String, String> data = (Map<String, String>) intent.getSerializableExtra(EXTRA_IMG_PARAMS);
handleUploadImg(isList, data);
}
}
}
private void handleUploadImg(List<String> isList, Map<String, String> data) {
try {
String upFileUrl = "替換為你自己的地址";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(upFileUrl);
// 要把數(shù)據(jù)封裝到post
/**
*
* httpmime-v4.2.3
* httpmime-4.3.5.jar 依賴 httpcore-4.3.2 -- MultiPartEntity.addPart()
* 以上兩個(gè)是不同的
* 我用的是 httpmime-v4.2.3 讶隐,本文最后有下載地址
*/
MultipartEntity entity = new MultipartEntity();
for (Map.Entry<String, String> entry : data.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
entity.addPart(key, new StringBody(value, Charset.forName("UTF-8")));
}
int isListSize = isList.size();
if (isListSize > 0) {
for (int i = 0, len = isListSize; i < len; i++) {
// 循環(huán)獲取每個(gè)image的路徑
String sourcePath = isList.get(i).getSourcePath();
// 將每一個(gè)圖片都轉(zhuǎn)成二進(jìn)制流文件
InputStream is = new FileInputStream(new File(sourcePath));
String filename = getImgName(sourcePath);
// 二進(jìn)制的流文件數(shù)據(jù)封裝
entity.addPart("upfile", new InputStreamBody(is, "multipart/form-data", filename));
}
}
post.setEntity(entity);
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("請(qǐng)求服務(wù)器出錯(cuò)");
}
String result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
Intent intent = new Intent(TestActivity.UPLOAD_RESULT);
intent.putExtra(BACK_RESULT, result);
sendBroadcast(intent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根據(jù)路徑獲取文件名
*
* @param imgPath
* @return
*/
private String getImgName(String imgPath) {
String temp[] = imgPath.replaceAll("\\\\", "/").split("/");
if (temp.length > 1) {
return temp[temp.length - 1];
} else {
return imgPath;
}
}
@Override
public void onCreate() {
super.onCreate();
Log.e("TAG", "onCreate");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("TAG", "onDestroy");
}
}
接下來是 TestActivity 代碼
public static final String UPLOAD_RESULT = "naple.test.UPLOAD_RESULT";
ArrayList<String> mDataList = new ArrayList<String>();
public class TestActivity extends Activity {
private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == UPLOAD_RESULT) {
String backResult = intent.getStringExtra(UploadImgService.BACK_RESULT);
handleResult(backResult);
}
}
};
private void handleResult(String backResult) {
//返回的結(jié)果處理
System.out.println(TAG, "上傳結(jié)果" + backResult);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver();
initView();
}
public void initView() {
// 布局文件就一個(gè) button
Button mUpBtn = (Button) findViewById(R.id.btn_upload);
mUpBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
doLoad();
}
});
}
private void doLoad(){
// 請(qǐng)求普通信息
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", "如果你需要傳給服務(wù)端用戶名的話");
//mDataList 存放圖片地址
UploadImgService.startUploadImg(this, mDataList, params);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(uploadImgReceiver);
}
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(UPLOAD_RESULT);
registerReceiver(uploadImgReceiver, filter);
}
}
IntentService修改UI
IntentService如果要進(jìn)行UI的修改,那么只能通過Handler來實(shí)現(xiàn)久又,或者使用廣播機(jī)制來通知修改UI巫延。
IntentService與AsyncTask的區(qū)別
對(duì)于異步更新UI來說,IntentService使用的是Serivce+handler或者廣播的方式地消,而AsyncTask是thread+handler的方式炉峰。
AsyncTask比IntentService更加輕量級(jí)一點(diǎn)。
Thread的運(yùn)行獨(dú)立于Activity脉执,當(dāng)Activity結(jié)束之后疼阔,如果沒有結(jié)束thread,那么這個(gè)Activity將不再持有該thread的引用半夷。
Service不能在onStart方法中執(zhí)行耗時(shí)操作婆廊,只能放在子線程中進(jìn)行處理,當(dāng)有新的intent請(qǐng)求過來都會(huì)線onStartCommond將其入隊(duì)列巫橄,當(dāng)?shù)谝粋€(gè)耗時(shí)操作結(jié)束后淘邻,就會(huì)處理下一個(gè)耗時(shí)操作(此時(shí)調(diào)用onHandleIntent),都執(zhí)行完了自動(dòng)執(zhí)行onDestory銷毀IntengService服務(wù)湘换。
有什么不足或者不對(duì)的地方宾舅,歡迎留言指正