如果沒興趣的可以直接看實例。
首先把 原文 搬過來:IntentService是Service類的子類,用來處理異步請求??蛻舳丝梢酝ㄟ^startService(Intent)方法傳遞請求給IntentService,IntentService通過worker thread處理每個Intent對象,執(zhí)行完一個Intent請求對象所對應(yīng)的工作之后,如果沒有新的Intent請求達到,則自動停止Service;否則執(zhí)行下一個Intent請求所對應(yīng)的任務(wù),執(zhí)行完所有的工作之后自動停止Service。
IntentService在處理事務(wù)時,還是采用的Handler方式,創(chuàng)建一個名叫ServiceHandler的內(nèi)部Handler,并把它直接綁定到HandlerThread所對應(yīng)的子線程。 ServiceHandler把處理一個intent所對應(yīng)的事務(wù)都封裝到叫做onHandleIntent的虛函數(shù);因此我們直接實現(xiàn)虛函數(shù)onHandleIntent,再在里面根據(jù)Intent的不同進行不同的事務(wù)處理就可以了。
說明:worker thread處理所有通過傳遞過來的請求,創(chuàng)建一個worker queue,一次只傳遞一個intent到onHandleIntent中,從而不必擔心多線程帶來的問題。處理完畢之后自動調(diào)用stopSelf()方法;默認實現(xiàn)了Onbind()方法,返回值為null;
模式實現(xiàn)了onStartCommand()方法,這個方法會放到worker queue中,然后在onHandleIntent()中執(zhí)行0。
使用IntentService需要兩個步驟:
1、寫構(gòu)造函數(shù)
2、復(fù)寫onHandleIntent()方法(根據(jù)Intent的不同進行不同的事務(wù)處理)
注意:IntentService的構(gòu)造函數(shù)一定是參數(shù)為空的構(gòu)造函數(shù),然后再在其中調(diào)用super("classname")這種形式的構(gòu)造函數(shù)。
因為Service的實例化是系統(tǒng)來完成的,而且系統(tǒng)是用參數(shù)為空的構(gòu)造函數(shù)來實例化Service的
---------------------以上是一些介紹和個人------------------------
寫一個Demo來模擬兩個耗時操作 Operation1與Operation2,
執(zhí)行完一個Intent請求對象所對應(yīng)的工作之后,如果沒有新的Intent請求達到,則自動停止Service;否則執(zhí)行下一個Intent請求所對應(yīng)的任務(wù),執(zhí)行完所有的工作之后自 動停止Service。
看是不是先執(zhí)行1,2必須等1執(zhí)行完才能執(zhí)行:
public class UploadImgService extends IntentService {
public UploadImgService() {
//必須實現(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ù),根據(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();
}
}
把生命周期方法全打印出來了,待會我們來看看它執(zhí)行的過程是怎樣的。接下來是Activity,在Activity中來啟動IntentService:
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//可以啟動多次,每啟動一次,就會新建一個work thread,但IntentService的實例始終只有一個
//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);
}
}
別急著運行看效果,還有配置Service,因為它繼承于Service,所以,它還是一個Service,一定要配置,否則是不起作用的
<service android:name="com.naplec.service.UploadImgService"></service>
自己看下打印的就應(yīng)該差不多明白了
以上呢是IntentService用法,現(xià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()
* 以上兩個是不同的
* 我用的是 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)獲取每個image的路徑
String sourcePath = isList.get(i).getSourcePath();
// 將每一個圖片都轉(zhuǎn)成二進制流文件
InputStream is = new FileInputStream(new File(sourcePath));
String filename = getImgName(sourcePath);
// 二進制的流文件數(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("請求服務(wù)器出錯");
}
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() {
// 布局文件就一個 button
Button mUpBtn = (Button) findViewById(R.id.btn_upload);
mUpBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
doLoad();
}
});
}
private void doLoad(){
// 請求普通信息
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如果要進行UI的修改,那么只能通過Handler來實現(xiàn),或者使用廣播機制來通知修改UI。
IntentService與AsyncTask的區(qū)別
對于異步更新UI來說,IntentService使用的是Serivce+handler或者廣播的方式,而AsyncTask是thread+handler的方式。
AsyncTask比IntentService更加輕量級一點。
Thread的運行獨立于Activity,當Activity結(jié)束之后,如果沒有結(jié)束thread,那么這個Activity將不再持有該thread的引用。
Service不能在onStart方法中執(zhí)行耗時操作,只能放在子線程中進行處理,當有新的intent請求過來都會線onStartCommond將其入隊列,當?shù)谝粋€耗時操作結(jié)束后,就會處理下一個耗時操作(此時調(diào)用onHandleIntent),都執(zhí)行完了自動執(zhí)行onDestory銷毀IntengService服務(wù)。
有什么不足或者不對的地方,歡迎留言指正