android开发实例-AsyncTask

啥状况啊,为什么上传图片浏览器就会刷新啊,文章都掉了好几次了。打开自动保存的内容,然后就显示在那边,返回键也木有。我决定不废话了。。

1.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=".MainActivity" >

    <TextView
        android:id="@+id/ShowMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />
    
    <Button 
        android:id="@+id/Start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载" 
        />
    
    <Button 
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停止" 
        />
    
    <ImageView
        android:id="@+id/imageShow"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

</LinearLayout>
View Code

2.MainActivity.xml

package com.mythou.asynctask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener
{
	private static final String TAG="wxpDeb";
	private TextView mShowLogTextView;
	private Button mPlayMusicButton;
	private Button mStopMusicButton;
	private MediaPlayer MediaCtrl;
	private DownLoad mDownLoad;
	private Context mContext;
	private ImageView mNetImageView;
	private Bitmap mDownLoadBtBitmap;
Dialog dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mContext = this;
		
		dialog=new Dialog(this);//等待对话框
		
		mShowLogTextView = (TextView)findViewById(R.id.ShowMsg);//下载状态显示
		mPlayMusicButton = (Button)findViewById(R.id.Start);//下载按钮
		mStopMusicButton = (Button)findViewById(R.id.stop);//停止按钮
		mNetImageView = (ImageView)findViewById(R.id.imageShow);//显示图片
		
		mPlayMusicButton.setOnClickListener(this);
		mStopMusicButton.setOnClickListener(this);
		//  Log.w(TAG, "Status:"+mDownLoad.getStatus());   
	}
	
	
	public void onClick(View v)
	{
		if (v==mPlayMusicButton)
		{  mShowLogTextView.setText("onPreExecute。。。begin downLoad");  
			dialog.setTitle("downLoad......");//点击之后立即弹出等待对话框
		   dialog.show();
			mDownLoad = new DownLoad();//注意一定要在这里实例化,否则第一次下载完毕之后如果再次点击下载按钮会报错会出错
		
		
			new Handler().postDelayed((new Runnable() {
				
				public void run() {
					// TODO Auto-generated method stub
					//传入下载图片的地
					mDownLoad.execute("http://www.baidu.com/img/bdlogo.gif");
				  
				}
			}), 3000);//为了突出等待效果,延时三秒
		
			  Log.w(TAG, "Status:"+mDownLoad.getStatus());   
			//这个参数难道是doInbackground()方法里的参数param?
			 Log.i(TAG, "execute() 执行");  
		}
		if (v==mStopMusicButton)
		{
			
			mDownLoad.onCancelled();
			
		}
	}  


	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	private class DownLoad extends AsyncTask<String, Integer, String> 
	{
        //onPreExecute方法在execute()后执行
        @Override  
        protected void onPreExecute() 
        {  
            Log.i(TAG, "onPreExecute() enter"); 
            Log.w(TAG, "onPreExecute_start_Status:"+mDownLoad.getStatus());   

        }  
          
        //doInBackground方法内部执行后台任务,不能在里面更新UI,否则有异常。
        @Override  
        protected String doInBackground(String... params) 
        {    Log.w(TAG, "doInBackground_start_Status:"+mDownLoad.getStatus());   
            Log.i(TAG, "doInBackground(String... params) enter");  
            Log.i(TAG, params.toString());  
        	URL imageUrl=null;
        	try 
        	{
    			imageUrl=new URL(params[0]);
    		} 
        	catch (MalformedURLException e) 
        	{
    			e.printStackTrace();
    			Log.e(TAG, e.getMessage());
    		}
    		try
    		{
    			//使用HttpURLConnection打开连接
    			HttpURLConnection urlConn=(HttpURLConnection)imageUrl.openConnection();
    			urlConn.setDoInput(true);
    			urlConn.connect();
    			//将得到的数据转化成InputStream
    			InputStream is=urlConn.getInputStream();
    			//将InputStream转换成Bitmap
    			mDownLoadBtBitmap=BitmapFactory.decodeStream(is);
    			is.close();
    			//不能在这里更新UI,否则有异常
    			//mNetImageView.setImageBitmap(bitmap);
    		}catch(IOException e)
    		{
    			Log.e(TAG,e.getMessage());
    		}
    		 Log.w(TAG, "doInBackground_end_Status:"+mDownLoad.getStatus());   
    		return "ok";
        }  
          
        //onProgressUpdate方法用于更新进度信息  
        @Override  
        protected void onProgressUpdate(Integer... progresses) 
        {   
            Log.i(TAG, "onProgressUpdate(Integer... progresses) enter");  
 
            mShowLogTextView.setText("onProgressUpdate Down loading..."); 
            Log.w(TAG, "onProgressUpdate_end_Status:"+mDownLoad.getStatus());   
        }  
          
        //onPostExecute用于doInBackground执行完后,更新界面UI。
        //result是doInBackground返回的结果
        @Override  
        protected void onPostExecute(String result) 
        
        {
        	dialog.dismiss();
        	Log.w(TAG, "onPostExecute_start_Status:"+mDownLoad.getStatus());   
            Log.i(TAG, "onPostExecute(Result result) called");  
            mShowLogTextView.setText("Down load finish result="+result);  
              
            mNetImageView.setImageBitmap(mDownLoadBtBitmap);
           
         
            Log.w(TAG, "onPostExecute_end_Status:"+mDownLoad.getStatus());   
        }  
          
        //onCancelled方法用于取消Task执行,更新UI
        @Override  
        protected void onCancelled() 
        {  
            Log.i(TAG, "onCancelled() called");  
            mShowLogTextView.setText("onCancelled"); 
            mNetImageView.setImageBitmap(null);
            //取消之后将imageview清空
        }  
    }

}

 

 

插!

posted @ 2013-07-23 09:20  wisimer  阅读(261)  评论(0编辑  收藏  举报