andorid------在線下載到內部存儲,並升級apk

對apk進行升級需要判斷versionCode是否一致,如果判斷下載的vesionCode比本地的versionCode大,則進行升級。

所以應該獲得本地的verisonCode的值,因此需要用到packagemanager類、packageinfo(封裝的是versionCode,versionName等)類

packagemanager類 通過context.getPackageManager()獲取,.packageinfo類通過manager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES)獲取


如何讓apk自動提示安裝呢

如下代碼

Uri uri = Uri.fromFile(new File(downloadPath));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);


好了 廢話不多說了上代碼


MainActivity.java

package com.example.android_install_apk1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

public class MainActivity extends Activity {
	private PackageUtils packageUtils;
	private ProgressDialog dialog;
	private String path = "http://192.168.0.103:8080/map/servlet/upGradeAction";
	private AlertDialog.Builder builder;
	private DownLoadMessage downLoadMessage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		boolean isUpgrade = false;
		builder = new Builder(this);
		builder.setTitle("信息提示");
		builder.setMessage("有新的版本,是否下載");
		builder.setNegativeButton("取消", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		builder.setPositiveButton("確定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String url = downLoadMessage.getUrl();
				new DownLoadAPK().execute(url);
			}
		});
		dialog = new ProgressDialog(this);
		dialog.setTitle("信息提示");
		dialog.setMessage("loading.....");
		packageUtils = new PackageUtils(this);
		int versionCode = packageUtils.getVersionCode();
		try {
			String json = new MyTask().execute(path).get();
			downLoadMessage = (DownLoadMessage) ParseUtils.parseJsonToObject(json, DownLoadMessage.class);
			isUpgrade = packageUtils.isUpgrade(versionCode, downLoadMessage.getVersionCode()); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (isUpgrade) {
			builder.create().show();
		}
	}

	public class DownLoadAPK extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected Void doInBackground(String... params) {
			//將apk下載
			byte[] apkByte = HttpUtils.downLoadApk(params[0]);
			
			FileOutputStream outputStream = null;
			
			try {
				outputStream = MainActivity.this.openFileOutput("android_install_apk1.apk", Context.MODE_PRIVATE);
				outputStream.write(apkByte, 0, apkByte.length);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (outputStream != null) {
					try {
						outputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}
			String downloadPath = MainActivity.this.getFilesDir()+"/android_install_apk1.apk";
			System.out.println("--->>"+downloadPath);
			//自動安裝apk
			Uri uri = Uri.fromFile(new File(downloadPath));
			Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(uri, "application/vnd.android.package-archive");
			startActivity(intent);
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			dialog.dismiss();
		}
	}
	
	public class MyTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			String json = HttpUtils.connAction(params[0]);
			return json;
		}
	}
	
}

PackageUtils.java

package com.example.android_install_apk1;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class PackageUtils {
	private PackageManager manager;
	private Context context;
	private PackageInfo info;
	
	public PackageUtils(Context context) {
		this.context = context;
		init();
	}
	
	public void init() {
		manager = context.getPackageManager();
		try {
			info = manager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 得到本地版本號
	 * @return
	 */
	public int getVersionCode() {
		return info.versionCode;
	}
	
	/**
	 * 得到版本名稱
	 * @return
	 */
	public String getVersionName() {
		return info.versionName;
	}
	
	public boolean isUpgrade(int oldVersionCode, int newVersionCode) {
		boolean flag = false;
		flag = newVersionCode>oldVersionCode?true:false;
		return flag;
	}
}

ParseUtils.java

package com.example.android_install_apk1;

import com.google.gson.Gson;

public class ParseUtils {

	public static Object parseJsonToObject(String json, Class c) {
		Gson gson = new Gson();
		Object obj = gson.fromJson(json, c);
		
		return obj;
	}
	
	public static String convertObjectToJson(Object obj) {
		String json = "";
		Gson gson = new Gson();
		json = gson.toJson(obj);
		
		return json;
	}
}

HttpUtils.java

package com.example.android_install_apk1;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;


public class HttpUtils {

	public static String connAction(String path) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(path);
		HttpResponse httpResponse = null;
		
		String json = "";
		try {
			httpResponse = httpClient.execute(httpPost);
			
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				json = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return json;
	}
	
	public static byte[] downLoadApk(String path) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(path);
		HttpResponse httpResponse = null;
		byte[] apkByte = null;
		
		try {
			httpResponse = httpClient.execute(httpPost);
			
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				apkByte = EntityUtils.toByteArray(httpResponse.getEntity());
				
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return apkByte;
	}
}

DownLoadMessage.java

package com.example.android_install_apk1;

public class DownLoadMessage {

	private int versionCode;
	private String versionName;
	private String url;
	public int getVersionCode() {
		return versionCode;
	}
	public void setVersionCode(int versionCode) {
		this.versionCode = versionCode;
	}
	public String getVersionName() {
		return versionName;
	}
	public void setVersionName(String versionName) {
		this.versionName = versionName;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	
	
}

如何出現錯誤歡迎大家留言糾正





發佈了31 篇原創文章 · 獲贊 21 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章