您的位置:首页 > 移动开发 > Android开发

android *** AsyncTask 代码

2016-02-05 21:43 501 查看
http://android-doc.com/reference/android/os/AsyncTask.html

xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >

<ImageView
android1:id="@+id/imageView1"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_alignParentLeft="true"
android1:layout_alignParentTop="true"
android1:layout_marginLeft="78dp"
android1:layout_marginTop="180dp" />

<Button
android1:id="@+id/button1"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_alignParentBottom="true"
android1:layout_marginBottom="78dp"
android1:layout_toRightOf="@+id/imageView1"
android1:text="下载图片" />

</RelativeLayout>


java

package com.example.tree;

import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

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.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AnalogClock;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

private Button button;
private ImageView imageView;
private final String IMAGE_PATH="http://www.baidu.com/img/bdlogo.gif";
private ProgressDialog dialog;
private final String TAG="MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "-onCreate-->>");
button=(Button)this.findViewById(R.id.button1);
imageView=(ImageView)this.findViewById(R.id.imageView1);
dialog=new ProgressDialog(MainActivity.this);
dialog.setTitle("提示框");
dialog.setMessage("正在下载图片,请稍后...");
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
button.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MyTask().execute(IMAGE_PATH);
}

});

}

class MyTask extends AsyncTask<String,Integer,byte[]>{

@Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
@Override
protected byte[] doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(params[0]);
byte[] result=null;
InputStream inputStream=null;
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
long file_length=httpResponse.getEntity().getContentLength();//文件总长度
int total_length=0;
byte[] data=new byte[1024];
int len=0;
if(httpResponse.getStatusLine().getStatusCode()==200){
//	result=EntityUtils.toByteArray(httpResponse.getEntity());
inputStream=httpResponse.getEntity().getContent();
while((len=inputStream.read(data))!=-1){
total_length+=len;
int progress_value=(int)((total_length/(float)file_length)*100);
publishProgress(progress_value);
outputStream.write(data, 0, len);
}
}
result=outputStream.toByteArray();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
httpClient.getConnectionManager().shutdown();
}

return result;
}

protected void onProgressUpdate(Integer...values){
super.onProgressUpdate(values);
dialog.setProgress(values[0]);

}
protected void onPostExecute(byte[] result){
super.onPostExecute(result);
Bitmap bitmap=BitmapFactory.decodeByteArray(result, 0, result.length);
imageView.setImageBitmap(bitmap);
dialog.dismiss();
}

}

protected void onStart(){
super.onStart();
Log.i(TAG, "-onStart-->>");
}

protected void onRestart(){
super.onRestart();
Log.i(TAG, "-onRestart-->>");
}

protected void onResume(){
super.onResume();
Log.i(TAG, "-onResume-->>");
}

protected void onPause(){
super.onPause();
Log.i(TAG, "-onPause-->>");
}

protected void onStop(){
super.onStop();
Log.i(TAG, "-onStop-->>");
}

protected void onDestroy(){
super.onDestroy();
Log.i(TAG, "-onDestroy-->>");
}

@Override
public 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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: