IntentService 上傳多圖

如果沒興趣的可以直接看實(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ì)的地方宾舅,歡迎留言指正

httpmime-v4.2.3

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市彩倚,隨后出現(xiàn)的幾起案子筹我,更是在濱河造成了極大的恐慌,老刑警劉巖帆离,帶你破解...
    沈念sama閱讀 217,084評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蔬蕊,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡哥谷,警方通過查閱死者的電腦和手機(jī)袁串,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門概而,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人囱修,你說我怎么就攤上這事赎瑰。” “怎么了破镰?”我有些...
    開封第一講書人閱讀 163,450評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵餐曼,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我鲜漩,道長(zhǎng)源譬,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,322評(píng)論 1 293
  • 正文 為了忘掉前任孕似,我火速辦了婚禮踩娘,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘喉祭。我一直安慰自己养渴,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,370評(píng)論 6 390
  • 文/花漫 我一把揭開白布泛烙。 她就那樣靜靜地躺著理卑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蔽氨。 梳的紋絲不亂的頭發(fā)上藐唠,一...
    開封第一講書人閱讀 51,274評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音鹉究,去河邊找鬼宇立。 笑死,一個(gè)胖子當(dāng)著我的面吹牛自赔,可吹牛的內(nèi)容都是我干的妈嘹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,126評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼匿级,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼蟋滴!你這毒婦竟也來了染厅?” 一聲冷哼從身側(cè)響起痘绎,我...
    開封第一講書人閱讀 38,980評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎肖粮,沒想到半個(gè)月后孤页,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,414評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡涩馆,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,599評(píng)論 3 334
  • 正文 我和宋清朗相戀三年行施,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了允坚。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,773評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蛾号,死狀恐怖稠项,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情鲜结,我是刑警寧澤展运,帶...
    沈念sama閱讀 35,470評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站精刷,受9級(jí)特大地震影響拗胜,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜怒允,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,080評(píng)論 3 327
  • 文/蒙蒙 一埂软、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧纫事,春花似錦勘畔、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蚊夫,卻和暖如春诉字,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背知纷。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評(píng)論 1 269
  • 我被黑心中介騙來泰國打工壤圃, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人琅轧。 一個(gè)月前我還...
    沈念sama閱讀 47,865評(píng)論 2 370
  • 正文 我出身青樓伍绳,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親乍桂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子冲杀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,689評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 本文出自 Eddy Wiki ,轉(zhuǎn)載請(qǐng)注明出處:http://eddy.wiki/interview-androi...
    eddy_wiki閱讀 3,265評(píng)論 0 20
  • 前言:本文所寫的是博主的個(gè)人見解睹酌,如有錯(cuò)誤或者不恰當(dāng)之處权谁,歡迎私信博主,加以改正憋沿!原文鏈接旺芽,demo鏈接 Serv...
    PassersHowe閱讀 1,413評(píng)論 0 5
  • 1.什么是Activity?問的不太多采章,說點(diǎn)有深度的 四大組件之一,一般的,一個(gè)用戶交互界面對(duì)應(yīng)一個(gè)activit...
    JoonyLee閱讀 5,731評(píng)論 2 51
  • 1运嗜、張浮休書 張蕓叟與石司理書云:“頃游京師,求謁先達(dá)之門悯舟,每聽歐陽文忠公担租、司馬溫公、王荊公之論抵怎,于行義文史為多翩活,...
    古陽閱讀 600評(píng)論 0 1
  • 忙,實(shí)在太忙盔粹!時(shí)間都去哪里了隘梨?工作,家庭舷嗡,社交轴猎,還有......微信!哪有時(shí)間再去讀什么書學(xué)什么習(xí)进萄。 但是捻脖,在知識(shí)...
    愛老虎更愛讀書閱讀 1,176評(píng)論 0 3