Thứ Hai, 15 tháng 7, 2013

Dùng timertask để download từ từ về

Đầu tiên là file giao diện:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

   <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show test"
        android:textSize="18sp"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="1"/>

</LinearLayout>

Tiếp đến là activity:

package example.bom.search;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.example.test.R;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Entity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class PlayMediaActivity extends Activity{
   TimerTask timetask;
   Timer t;
   ImageView imageview;
   TextView textview;
   ProgressDialog progressdialog;
   int test=0;
   private Handler threadHandler = new Handler() {
       public void handleMessage(Message msg) {
           // whenever the Thread notifies this handler we have
           // only this behavior
      if(msg.what==100){
      textview.setText("Down duoc "+msg.getData().getInt("progress")+"%");
      progressdialog.setProgress(msg.getData().getInt("progress"));
      Log.d("phanbom","Vao duoc handler:"+msg.getData().getInt("progress"));
      }else{
      dismissDialog(0);
               String imagepath = Environment.getExternalStorageDirectory().toString()+"/image.png";
               imageview.setImageDrawable(Drawable.createFromPath(imagepath));
      }
         
         
       }
   };
   @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.example_bom_search_playmedia);
imageview = (ImageView)findViewById(R.id.image);
textview = (TextView)findViewById(R.id.textview);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
 t = new Timer();
 t.scheduleAtFixedRate(new Mytimetask("http://marakana.com/images/generic-user.png"), 1000, 300);
}
});
}
 
  @Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
  progressdialog = new ProgressDialog(this);
  progressdialog.setTitle("Down image");
  progressdialog.setMessage("Downloading..");
  progressdialog.setIndeterminate(false);
  progressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  progressdialog.setProgress(0);
  progressdialog.setMax(100);
  progressdialog.setCancelable(true);
  progressdialog.show();
  return progressdialog;

}

   

public class Mytimetask extends TimerTask{
byte data[];
int count;
    InputStream input;
    OutputStream output;
   
    int length_of_file,truoc=0,sobyte,total;
    public Mytimetask(String url1){
        showDialog(0);
                     URL url = null;
                                   try {
                                       url = new URL(url1);                    
                                       URLConnection con;
                                           con = url.openConnection();
                                       con.setConnectTimeout(10000);
                                       con.connect();
                                       length_of_file = con.getContentLength();
                                       Log.d("phanbom","Do dai file:"+length_of_file);
                                       input = new BufferedInputStream(con.getInputStream());
                                       output = new FileOutputStream("/sdcard/image.png");
                                       data = new byte[length_of_file];
                                       total = 0;
                                       sobyte = length_of_file/100;
                                   
                                     
                                   }catch(SocketTimeoutException e){
                                           e.printStackTrace();
                            }catch(IOException e){
                                   e.printStackTrace();
                            }
    }
@Override
public void run() {
// TODO Auto-generated method stub
try {
if((length_of_file-total)<sobyte) sobyte = length_of_file-total;
count=input.read(data,truoc,sobyte);
if (count!=0) {
    //count la so byte duoc doc mot lan
    // Bien total de luu so luong byte da duoc doc
    total += count;
   
    Log.d("phanbom","Luong byte chuyen va total:"+count+"|"+total+"|"+length_of_file);
    float pro = (total*100)/length_of_file;
       Message messageToThread = new Message();
                               Bundle messageData = new Bundle();
                               messageToThread.what = 100;
                              Log.d("phanbom","% la :"+total+"|"+pro);
                               messageData.putInt("progress",(int)pro);
                               messageToThread.setData(messageData);
                               threadHandler.sendMessage(messageToThread);
                             
   
   
    //sau do viet vao file tren sdcard voi du lieu trong mang data va so byte
    //moi lan viet la count
     try {
output.write(data,truoc,count) ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     truoc = total;
   
}else{
output.flush();
                                output.close();
                                Message messageToThread = new Message();
                                Bundle messageData = new Bundle();
                                messageToThread.what = 1000;
                                messageData.putString("test","OK");
                                messageToThread.setData(messageData);
                                threadHandler.sendMessage(messageToThread);
  t.cancel();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


}

Không có nhận xét nào:

Đăng nhận xét