Android開發之使用Handler封裝下載圖片工具類

來源:互聯網
上載者:User

標籤:android   dialog   callback   http   interface   

          如果每下載一張圖片,就得重寫一次Http協議,多線程的啟動和handler的資訊傳遞就顯得太麻煩了,我們直接來封裝一個工具類,便於我們以後在開發時隨時可以調用。

 (1)在資訊清單檔添加許可權

  <uses-permission android:name="android.permission.INTERNET"/>

(2)編輯工具類

package com.example.g05_handler;import java.io.IOException;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import android.annotation.SuppressLint;import android.app.ProgressDialog;import android.content.Context;import android.os.Handler;import android.os.Message;import android.util.Log;public class DownLoad {private ProgressDialog dialog;public DownLoad(Context context) {// TODO Auto-generated constructor stubdialog = new ProgressDialog(context);dialog.setTitle("提示");dialog.setMessage("玩命載入中");}@SuppressLint("HandlerLeak")public void Down(final String path, final DownLoadCallback callback) {final Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);byte[] result = (byte[]) msg.obj;callback.download(result);if (msg.what == 1) {dialog.dismiss();}}};class MyThread implements Runnable {@Overridepublic void run() {// TODO Auto-generated method stubHttpClient client = new DefaultHttpClient();HttpGet httpGet = new HttpGet(path);try {HttpResponse httpResponse = client.execute(httpGet);Log.i("TAG", "------>"+ httpResponse.getStatusLine().getStatusCode());if (httpResponse.getStatusLine().getStatusCode() == 200) {byte[] result = EntityUtils.toByteArray(httpResponse.getEntity());Message message = Message.obtain();message.obj = result;message.what = 1;handler.sendMessage(message);}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (client != null) {client.getConnectionManager().shutdown();}}};}new Thread(new MyThread()).start();dialog.show();}public interface DownLoadCallback {public void download(byte[] data);}}

    (3)調用該工具類

package com.example.g05_handler;import com.example.g05_handler.DownLoad.DownLoadCallback;import android.os.Bundle;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.view.Menu;import android.view.View;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends Activity {    private Button button;    private ImageView imageView;    private final String path="http://avatar.csdn.net/D/7/5/1_u013900875.jpg";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button=(Button)this.findViewById(R.id.button1);imageView=(ImageView)this.findViewById(R.id.imageView1);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubDownLoad downLoad=new DownLoad(MainActivity.this);downLoad.Down(path, new DownLoadCallback() {@Overridepublic void download(byte[] data) {// TODO Auto-generated method stubBitmap bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);imageView.setImageBitmap(bitmap);}});}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.