android開發實例-AsyncTask

啥情況啊,爲何上傳圖片瀏覽器就會刷新啊,文章都掉了好幾回了。打開自動保存的內容,而後就顯示在那邊,返回鍵也木有。我決定不廢話了。。java

1.activity_main.xmlandroid

<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.xmlapache

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清空
        }  
    }

}

 

 

插!瀏覽器

相關文章
相關標籤/搜索