在android開發當中,主線程(UI線程)是不允許處理複雜的耗時操作的,否則會導致UI線程阻塞,因此對此類操作應該使用子線程處理,一般會使用到AsyncTask異步任務和handler多線程來處理,並且在子線程中是不允許修改UI線程元素的,因此會使用到異步回調方法;下面例子通過AsyncTask和handler例子說明;
首先建立佈局文件activity_main.xml,分別定義下載按鈕和獲取信息按鈕
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.picdown.MainActivity" >
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="下載" />
<Button
android:id="@+id/testbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="測試線程"
/>
</LinearLayout>
該例子是關於圖片的,新建一個實體類Pic.java
package com.example.picdown;
public class Pic {
private String name;
private String url;
private String type;
Pic(String name,String url,String type){
setName(name);
setUrl(url);
setType(type);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
回到MainActivity當中實現下載功能和圖片信息獲取功能:
package com.example.picdown;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.animation.ArgbEvaluator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private Button btn,testbtn;
private ImageView iv;
private ProgressDialog mProgressDialog;
private DownloadAsyncTask mTask;
private static final String PATH = "http://www.baidu.com/img/bdlogo.png";
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
public void initView(){
btn =(Button) findViewById(R.id.btn);
testbtn=(Button) findViewById(R.id.testbtn);
iv=(ImageView) findViewById(R.id.iv);
btn.setOnClickListener(this);
testbtn.setOnClickListener(this);
//初始化handler對象
handler =new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==1){
Pic pic =(Pic) msg.obj;
String name =pic.getName();
String url= pic.getUrl();
String type =pic.getType();
System.out.println("圖片名:"+name+";圖片地址:"+url+";圖片類型:"+type);
Toast.makeText(getApplicationContext(), "圖片名:"+name+";圖片地址:"+url+";圖片類型:"+type, Toast.LENGTH_SHORT).show();
}
}
};
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
downImg();
break;
case R.id.testbtn:
new Thread(new Runnable(){
public void run() {
Pic pics =new Pic("百度logo",PATH,"jpg圖片");
Message msg =handler.obtainMessage();
msg.what=1;
msg.obj=pics;
handler.sendMessage(msg);
}}).start();
break;
}
}
private void downImg(){
// 執行異步線程
mTask = new DownloadAsyncTask();
mTask.execute(PATH);
}
private class DownloadAsyncTask extends AsyncTask<String, Integer, Bitmap>{
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap =null;
try{
URL url = new URL(params[0]);
HttpURLConnection con =(HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.connect();
InputStream inputstream =con.getInputStream();
bitmap=BitmapFactory.decodeStream(inputstream);
inputstream.close();
}catch(Exception e){
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
iv.setImageBitmap(result);//設置圖片
}
}
}
最後不要忘了在AndroidManifest.xml當中添加訪問網絡的權限
<uses-permission android:name="android.permission.INTERNET"/>