Android中HTTP 檔案下載

Android中HTTP 檔案下載

Android中HTTP 檔案下載

 

利用java的httpclicent+HttpResponse+thread 讓程式可以執行下載(否則gui無法等待網路),利用Handler實做可以設定gui的timer,利用HttpResponse.getEntity().getContentLength();取得網路檔案大小,利用Toast.makeText顯示及時提示訊息,歡迎有興趣的同好一起來C/P。

 

package com.example.framelayout_http_download;
import com.example.framelayout_http_download.MainActivity.ButListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.view.Menu;
///////////////////////////////
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
///////////////////////////////////////
import android.view.View;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.view.ViewGroup.MarginLayoutParams;
import android.app.ActionBar.LayoutParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.net.Uri;
public class MainActivity extends Activity {
FrameLayout FrameLayout1;
DisplayMetrics metrics;
TextView TextView1;
Button Button1;
//WebView WebView1;
String SDPATH;
Thread thread;
int check;
int downloadselect;
long filesize,downloadsize;
Handler mHandlerTime;
int FILESIZE = 4 * 1024;
private DownloadManager downloadManager;
private SharedPreferences prefs;
private static final String DL_ID = "downloadId";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/////////////////////////////////////////
requestWindowFeature(Window.FEATURE_NO_TITLE);   //全螢幕設定
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
metrics = new DisplayMetrics();//抓取螢幕大小
getWindowManager().getDefaultDisplay().getMetrics(metrics);
/////////////////////////////////////////
FrameLayout1 = new FrameLayout(this);
FrameLayout.LayoutParams lparam1 = new FrameLayout.LayoutParams(metrics.widthPixels,metrics.heightPixels);
FrameLayout1.setLayoutParams(lparam1);
this.setContentView(FrameLayout1);
////////////////////////////////////////
Button1=new Button(this);
FrameLayout.LayoutParams layoutParams_Button = new FrameLayout.LayoutParams(metrics.widthPixels/4, metrics.heightPixels/4);
layoutParams_Button.gravity = Gravity.LEFT|Gravity.TOP;
layoutParams_Button.leftMargin = 0;//X
layoutParams_Button.topMargin = 0;//Y
Button1.setLayoutParams(layoutParams_Button);
Button1.setText("下載");
FrameLayout1.addView(Button1);
TextView1=new TextView(this);
FrameLayout.LayoutParams layoutParams_TextView = new FrameLayout.LayoutParams(metrics.widthPixels/4, metrics.heightPixels/4);
layoutParams_TextView.gravity = Gravity.LEFT|Gravity.TOP;
layoutParams_TextView.leftMargin = 0;//X
layoutParams_TextView.topMargin = metrics.heightPixels/4;//Y
TextView1.setLayoutParams(layoutParams_TextView);
TextView1.setText("請點選 下載按鈕");
FrameLayout1.addView(TextView1);
/*
	    WebView1=new WebView(this);
	    FrameLayout.LayoutParams layoutParams_WebView = new FrameLayout.LayoutParams(metrics.widthPixels, metrics.heightPixels/4*3);
	    layoutParams_Button.gravity = Gravity.LEFT|Gravity.TOP;
	    layoutParams_Button.leftMargin = 0;//X
	    layoutParams_Button.topMargin = metrics.heightPixels/4;//Y
	    WebView1.setLayoutParams(layoutParams_WebView);
	    WebView1.loadUrl("http://www.google.com/");
	    FrameLayout1.addView(WebView1);
	    */
check=0;
filesize=0;
downloadsize=0;
downloadselect=0;
mHandlerTime = new Handler();
Button1.setOnClickListener(new ButListener());
File df1 = new File("sdcard/DownLoad/PPTV.exe");
File df2 = new File("sdcard/DownLoad/pptv.png");
if (df1.exists())
df1.delete();
if (df2.exists())
df2.delete();
}
public Runnable mDownload = new Runnable()
{
@Override
public void run()
{
String REMOTE_FILE_URL=new String();
if(downloadselect==0)
{
REMOTE_FILE_URL="http://apk.ottclub.info/exe/PPTV.exe";
//downloadselect++;
}
else
{
REMOTE_FILE_URL="http://apk.ottclub.info/exe/icons/pptv.png";
//downloadselect=0;
}
int BUFFER = 1024;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REMOTE_FILE_URL);
try
{
HttpResponse response = httpClient.execute(httpGet);
InputStream in = response.getEntity().getContent();
filesize=response.getEntity().getContentLength();
FileOutputStream out;
if(downloadselect==0)
{
out = new FileOutputStream(new File("sdcard/DownLoad/PPTV.exe"));
downloadselect++;
}
else
{
out = new FileOutputStream(new File("sdcard/DownLoad/pptv.png"));
downloadselect=0;
}
byte[] b = new byte[BUFFER];
int len = 0;
downloadsize=0;
while((len=in.read(b))!= -1)
{
downloadsize+=len;
out.write(b,0,len);
}
in.close();
out.close();
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
//httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
check=1;
}
}
};
@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;
}
private final Runnable timerRun = new Runnable()
{
public void run()
{
if( (thread!=null) && (check==0))
{
String StrPercent="目前下載百分比:"+String.valueOf( (((float)downloadsize/(float)filesize) *100))+"%";
TextView1.setText("");
TextView1.append("下載中請稍後....\n");
TextView1.append(StrPercent);
mHandlerTime.postDelayed(this, 1000);
}
if( (thread!=null) && (check==1))
{
TextView1.setText("");
TextView1.append("下載完成\n");
TextView1.append("請到指令目錄查看\n");
thread.interrupt();
thread=null;
Button1.setEnabled(true);
}
// 若要取消可以寫一個判斷在這決定��否啟動下一次即可
}
};
class ButListener implements OnClickListener
{
public void onClick(View v)
{
if(downloadselect==0)
{
Toast.makeText(MainActivity.this, "準備 利用執行緒下載檔案 PPTV.exe...", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "準備 利用執行緒下載檔案 pptv.png...", Toast.LENGTH_SHORT).show();
}
Button1.setEnabled(false);
thread =new Thread(mDownload);
thread.start();
mHandlerTime.postDelayed(timerRun, 1000);
/*
			while(check==0)
			{
				TextView1.setText("");
				TextView1.append("下載完成\n");
				TextView1.append("請到指令目錄查看\n");
				thread.interrupt();
				thread=null;
			}
			check=0;
			*/
}
}
}

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *