一般的安卓app都有自動更新功能,實現app的更新,以讓用戶體驗新版本的功能。
代碼比較簡單,當用戶進入app中,首先會檢驗當前app的版本號與服務器的版本號,如果當前版本號小於服務器的版本號,則提示用戶更新app。
/**
* 獲取到當前的本地版本
*/
UpdateInformation.localVersion = MyApplication
.getInstance()
//包管理獨享
.getPackageManager()
//包信息
.getPackageInfo(
MyApplication.getInstance()
.getPackageName(), 0).versionCode;
/**
* 獲取到當前的版本名字
*/
UpdateInformation.versionName = MyApplication
.getInstance()
.getPackageManager()
.getPackageInfo(
MyApplication.getInstance()
.getPackageName(), 0).versionName;
通過PackageInfo這個類可以得到app相應的一些信息;
下面來看具體下載apk的代碼,這裏我使用AsyncTask來執行異步任務,首先把一個最新的apk放到服務器端的根目錄下(root);這裏我就不做說明了哈。
class DowoLoadTask extends AsyncTask<Void,Void,Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://10.88.88.88:8080/gpay/Chamberlain.apk");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
if(connection.getResponseCode()==200){
fileMax = connection.getContentLength();
InputStream is = connection.getInputStream();
byte buffer[] = new byte[1024];
int length = 0;
do{
length = is.read(buffer);
Log.e("length",length+"");
if(length<0){
downloadFinish = 100;
break;
}
fos.write(buffer,0,length);
progress = progress + length;
Log.e("fileMax", fileMax+"");
Log.e("progressssss",progress+ "");
double progree = ((double)progress / (double)fileMax);
Log.e("progreeeeeeeee",progree+"");
int pro = (int) (progree * 100);
Log.e("progresss",pro+"");
download_handler.sendEmptyMessage(pro);
}while(true);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if(downloadFinish == 100){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + download_file.getAbsolutePath()),"application/vnd.android.package-archive");
SecondActivity.this.startActivity(intent);
}
super.onPostExecute(aVoid);
}
}
然後通過handler來改變progressBar的進度
private Handler download_handler = new Handler(){
@Override
public void handleMessage(Message msg) {
progressBar.setProgress(msg.what);
super.handleMessage(msg);
}
};
代碼看起來很簡單,項目截圖如下:
提示下載
下載完成後開始安裝apk
這塊引用的事別人的圖片! 介紹完畢。哈哈