1. 程式人生 > >Android實現應用下載並自動安裝apk包

Android實現應用下載並自動安裝apk包

安裝:

String str = "/CanavaCancel.apk"; 
String fileName = Environment.getExternalStorageDirectory() + str; 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive"); 
startActivity(intent);


解除安裝:

Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");   
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);   
startActivity(uninstallIntent);


下載部分:

protected File downLoadFile(String httpUrl) {
                // TODO Auto-generated method stub
                final String fileName = "updata.apk";
                File tmpFile = new File("/sdcard/update");
                if (!tmpFile.exists()) {
                        tmpFile.mkdir();
                }
                final File file = new File("/sdcard/update/" + fileName);

                try {
                        URL url = new URL(httpUrl);
                        try {
                                HttpURLConnection conn = (HttpURLConnection) url
                                                .openConnection();
                                InputStream is = conn.getInputStream();
                                FileOutputStream fos = new FileOutputStream(file);
                                byte[] buf = new byte[256];
                                conn.connect();
                                double count = 0;
                                if (conn.getResponseCode() >= 400) {
                                        Toast.makeText(Main.this, "連線超時", Toast.LENGTH_SHORT)
                                                        .show();
                                } else {
                                        while (count <= 100) {
                                                if (is != null) {
                                                        int numRead = is.read(buf);
                                                        if (numRead <= 0) {
                                                                break;
                                                        } else {
                                                                fos.write(buf, 0, numRead);
                                                        }

                                                } else {
                                                        break;
                                                }

                                        }
                                }

                                conn.disconnect();
                                fos.close();
                                is.close();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block

                                e.printStackTrace();
                        }
                } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block

                        e.printStackTrace();
                }

                return file;
        }
//開啟APK程式程式碼

private void openFile(File file) {
                // TODO Auto-generated method stub
                Log.e("OpenFile", file.getName());
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(android.content.Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file),
                                "application/vnd.android.package-archive");
                startActivity(intent);
        }

 

完整程式碼:

package com.isufe.edu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class DownloadActivity extends Activity {

	private String strURL = "";
	File file2 = new File(Environment.getExternalStorageDirectory() + "");
	private int downloaded = 0;
	private TextView processTv;

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Bundle bundle = msg.getData();
			int process = bundle.getInt("process");
			//System.out.println("Handler進度:"+process);

			processTv.setText("正在下載:"+process+"%");
		};
	};
	
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_download);
		processTv = (TextView) findViewById(R.id.download_process);
		Intent intent = getIntent();
		strURL = intent.getStringExtra("url");
		
		if (!strURL.equals("")) {
			new Thread() {
				public void run() {
					openFile(downLoadFile(strURL));
				};
			}.start();

		}

	}

	protected File downLoadFile(String httpUrl) {
		// TODO Auto-generated method stub
		final String fileName = "isufe.apk";
		File tmpFile = new File("/sdcard/isufe");
		if (!tmpFile.exists()) {
			tmpFile.mkdir();
		}
		final File file = new File("/sdcard/isufe/" + fileName);
		long fileLength = 0l;

		try {
			URL url = new URL(httpUrl);
			try {
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				InputStream is = conn.getInputStream();
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buf = new byte[256];
				conn.connect();
				double count = 0;
				if (conn.getResponseCode() >= 400) {
					Toast.makeText(DownloadActivity.this, "連線超時",Toast.LENGTH_SHORT).show();
				} else {
					fileLength = conn.getContentLength();
					int fileDownload = 0;
					//System.out.println("檔案大小:"+fileLength);
					while (count <= 100) {
						if (is != null) {
							
							Message msg = new Message();
							Bundle bundle = new Bundle();
							
							int numRead = is.read(buf);
							fileDownload = fileDownload + numRead;
							
							downloaded = (int) (fileDownload*100/fileLength);
							//System.out.println("已下載:"+downloaded+"");
							bundle.putInt("process", downloaded);
							msg.setData(bundle);
							handler.sendMessage(msg);
							if (numRead <= 0) {
								break;
							} else {
								fos.write(buf, 0, numRead);
							}

						} else {
							break;
						}

					}
				}

				conn.disconnect();
				fos.close();
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block

				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		}

		return file;
	}

	// 開啟APK程式程式碼

	private void openFile(File file) {
		// TODO Auto-generated method stub
		Log.e("OpenFile", file.getName());
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}

}