2015年3月18日 星期三

[Android] AsyncTask (download picture)

remember to add permission in the manifest.xml , < uses-permission android:name="android.permission.INTERNET" / >

the code as below:

MainActivity.java
package tw.brad.android.book.MyAsyncTask;

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


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
 private View start, end, rm_pic;
 private TextView mesg;
 private MyMealTime task;
 private ImageView imView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  start = findViewById(R.id.start);
  rm_pic = findViewById(R.id.rm_pic);
  end = findViewById(R.id.end);
  mesg = (TextView) findViewById(R.id.msg);
  imView = (ImageView)findViewById(R.id.ImageView01);

  start.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    task = new MyMealTime();
    //傳遞多個參數給AsyncTask運作處理
    task.execute("http://spaceflightnow.com/news/n0211/04soho/sun.jpg");
   }
  });
  
  rm_pic.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // 提早結束AsyncTask
    
    Bitmap tmp = BitmapFactory.decodeResource(getResources(), R.drawable.photo_not_available);
    
    //setImageBitmap=> Sets a Bitmap as the content of this ImageView.是设置其内容
    imView.setImageBitmap(tmp);
    
    //setBackgroundResource => Set the background to a given resource.是设置背景
//    imView.setBackgroundResource(R.drawable.photo_not_available);
   }
  });
  
  end.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // 提早結束AsyncTask
    if (task != null && !task.isCancelled()) {
     task.cancel(true);
    }
   }
  });
 }

 private class MyMealTime extends AsyncTask< String, Integer, String > {
  private String[] name;
  private boolean isOver;
  int i;

  @Override
  protected String doInBackground(String... names) {
   i=0;
   name = names;
   Log.e("name[0]",name[0]);
   downloadFile(name[0]);
   
   while(true){
    try {
     publishProgress(i++);
     Thread.sleep(1000);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } // 暫停休眠
    
    
    if(i>5){
     break;
    }
    
    // 如果提早結束
    if (isCancelled()) {
     break;
    }
   }
   return null;
  }


  @Override
  protected void onCancelled() {
   super.onCancelled();

  }

  @Override
  protected void onPostExecute(String result) {
   super.onPostExecute(result);
   // 將接收執行結束厚的結果參數顯示在使用者介面
   imView.setImageBitmap(bmImg);
  }

  @Override
  protected void onPreExecute() {
   super.onPreExecute();
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
   super.onProgressUpdate();
   mesg.setText( values[0]+ " sec " );
   if(bmImg!=null){
    imView.setImageBitmap(bmImg);
   }
  }

 }

 private Bitmap bmImg=null;
 private Bitmap downloadFile(String fileUrl){
  URL myFileUrl =null; 
  
  try {
   myFileUrl= new URL(fileUrl);
  } catch (MalformedURLException e) 
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  try {
   HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
   conn.setDoInput(true);
   conn.connect();
   int length = conn.getContentLength();
   int[] bitmapData =new int[length];
   byte[] bitmapData2 =new byte[length];
   InputStream is = conn.getInputStream();
   
   bmImg = BitmapFactory.decodeStream(is);

  } 
  catch (IOException e) 
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return bmImg;
 } 
}




activity_main.xml



    

沒有留言:

張貼留言