其實這不是什么難事了,都有熱更新的技術了,只是記錄一下,大神勿嘲笑。
先說下思路,首先要有更新的接口,只要進入app,就監測一下接口,是否更新,更新的話,檢測本地版本是否低于接口返回的版本,低的話,就根據返回的路徑下載apk更新。接口返回的字段起碼有 更新標志、更新版本,更新描述,apk下載地址。
android硬件檢測程序。更新標志應該有三種狀態,更新,詢問更新,強制更新,可以啟動一個Service(不要忘記在清單文件中注冊)來進行檢查更新以及下載的工作;
這下面就是?Service里的全部代碼,也不是很難理解,重要的地方都有注釋。寫好Service后,在代碼中?startService()啟動就可以了。
這里面彈出了一個訊問框,需要在清單文件中 加入權限, ?,這是彈出全局訊問框的權限。
apk是什么。import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
android版本。import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
android。import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
安卓版本?import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.sdtz.wenmingweifang.R;
import com.example.sdtz.wenmingweifang.Tool.OkHttpUtil;
import com.example.sdtz.wenmingweifang.Util.App;
import com.example.sdtz.wenmingweifang.Util.MyUrl;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by sdtz on 2017/7/1.
*/
public class UpdateService extends Service {
private ProgressBar mProgressBar;//進度條
private TextView tv1;
private TextView tv2;
private String url = MyUrl.Httpurl;
private String VersionCode;
private String result;
private App app;
private String mSavePath;//apk保存地址
private String mVersion_path;
private String mVersion_name = "app.apk";//apk名
private float length;
private Dialog mDownloadDialog;//對話框
private int mProgress;//進度值
private static final int DOWNLOADING = 1;//apk下載中
private static final int DOWNLOAD_FINISH = 2;//apk下載完畢
private boolean mIsCancel = false;//是否取消下載標示符
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private Handler mUpdateProgressHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what){
case DOWNLOADING:
// 設置進度條
mProgressBar.setProgress(mProgress);
tv1.setText( mProgress + "/100");
float len = length/1024/1024;//將length轉換為M單位
float b = (float)(Math.round(len*100))/100;//保留兩位小數點
tv2.setText( b+"M");
break;
case DOWNLOAD_FINISH:
// 隱藏當前下載對話框
mDownloadDialog.dismiss();
// 安裝 APK 文件
installAPK();
break;
default:
break;
}
};
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
VersionCode = getVersionName();
/* getJsonReuslt();*/
new OkHttpUtil().getJson(MyUrl.appdown, new OkHttpUtil.HttpCallBack() {
@Override
public void onSusscess(String data) throws JSONException {
JSONObject jo1 = new JSONObject(data);
app = new App();
app.setVersion(jo1.getString("version").toString());
app.setDescription(jo1.getString("description").toString());
app.setUrl(MyUrl.Httpurl+jo1.getString("url").toString());
app.setUpdate_flag(jo1.getString("update_flag").toString());
mVersion_path = app.getUrl();
//手機當前版本
String phoneVersion = VersionCode.substring(0,VersionCode.lastIndexOf("."));
Double jiekou = Double.parseDouble(app.getVersion());
Double bendi = null;
try {
bendi = Double.parseDouble(getVersionName());
} catch (Exception e) {
e.printStackTrace();
}
Log.d("==","接口:"+jiekou+"本地:"+bendi+"::"+app.toString());
//本地版本 與 接口返回版本 不一致,并且 更新標志為1 ,則更新
if( !VersionCode.equals(app.getVersion()) && (jiekou>bendi) && app.getUpdate_flag().equals("1")){
Log.d("==","::進入");
showDialog(app.getDescription());
}else if( !VersionCode.equals(app.getVersion()) && (jiekou>bendi) && app.getUpdate_flag().equals("2")){
showDownloadDialog();
}
}
});
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
/*
* 獲取當前程序的版本號
*/
private String getVersionName() throws Exception{
//獲取packagemanager的實例
PackageManager packageManager = getPackageManager();
//getPackageName()是你當前類的包名,0代表是獲取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
return packInfo.versionName;
}
private void showDialog(String drc) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this,AlertDialog.THEME_HOLO_LIGHT);
builder.setMessage(drc);
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
showDownloadDialog();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setCanceledOnTouchOutside(true);
alertDialog.show();
alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(Color.GREEN);
alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setTextColor(Color.RED);
}
/*
* 開啟新線程下載文件
*/
private void downloadAPK() {
new Thread(new Runnable() {
@Override
public void run() {
try{//檢查sd是否掛載
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String sdPath = Environment.getExternalStorageDirectory() + "/";
mSavePath = sdPath + "WenmingDownload";
File dir = new File(mSavePath);
if (!dir.exists())
dir.mkdir();
// 下載文件
HttpURLConnection conn = (HttpURLConnection) new URL(mVersion_path).openConnection();
conn.connect();
InputStream is = conn.getInputStream();
length = conn.getContentLength();
File apkFile = new File(mSavePath, mVersion_name);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
byte[] buffer = new byte[1024];
while (!mIsCancel){
int numread = is.read(buffer);
count += numread;
// 計算進度條的當前位置
mProgress = (int) ((count/length) * 100);
// 更新進度條
mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);
// 下載完成
if (numread < 0){
mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
fos.write(buffer, 0, numread);
}
fos.close();
is.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
/*
* 下載到本地后執行安裝
*/
protected void installAPK() {
File apkFile = new File(mSavePath, mVersion_name);
if (!apkFile.exists())
return;
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file://" + apkFile.toString());
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
/*
* 顯示正在下載對話框
*/
protected void showDownloadDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("版本更新,下載中。。。");
View view = LayoutInflater.from(this).inflate(R.layout.dialog_progress, null);
mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress);
tv1 = (TextView) view.findViewById(R.id.tv1);
tv2 = (TextView) view.findViewById(R.id.tv2);
builder.setView(view);
mDownloadDialog = builder.create();
mDownloadDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
mDownloadDialog.show();
// 下載文件
downloadAPK();
}
}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态