今天整理了一個簡單的更新下載Demo(包括進入主頁自動檢測版本和點擊按鈕檢查版本)
先上圖:
image.png
image.png
image.png
image.png
Apk版本托管我選擇了Fir.im
添加加載視圖 (網絡訪問時防止由于網絡原因加載時間過長)
private void showLoadingView() {
PgDialog = new ProgressDialog(mContext);
PgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
PgDialog.setCancelable(false);
PgDialog.setMessage("正在加載,請稍后");
}
防止多次點擊
private static long lastClickTime = 0;
private final static int SPACE_TIME = 500;
public synchronized static boolean isDoubleClick() {
long currentTime = System.currentTimeMillis();
boolean isClick2;
isClick2 = currentTime - lastClickTime >= SPACE_TIME;
lastClickTime = currentTime;
return isClick2;
}
獲取應用的版本號
public static int getVersionCode(Context context) {
int versionCode1 = 0;
try {
if(context.getPackageManager()!=null){
// 獲取軟件版本號,對應AndroidManifest.xml下android:versionCode
versionCode1 = context.getPackageManager().getPackageInfo(
getPackageName(context), 0).versionCode;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode1;
}
/**
* 獲取應用的包名
**/
public static String getPackageName(Context context) {
return context.getPackageName();
}
打開文件 (添加兼容7.0手機的方案)
/**
* 打開文件
* 兼容7.0
*
* @param context activity
* @param file File
* @param contentType 文件類型如:文本(text/html)
* 當手機中沒有一個app可以打開file時會拋ActivityNotFoundException
*/
public static void startActionFile(Context context, File file, String contentType) throws ActivityNotFoundException {
if (context == null) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//增加讀寫權限
intent.setDataAndType(getUriForFile(context, file), contentType);
if (!(context instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}
private static Uri getUriForFile(Context context, File file) {
if (context == null || file == null) {
throw new NullPointerException();
}
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", file);
} else {
uri = Uri.fromFile(file);
}
return uri;
}
顯示升級提示
/**
* 顯示升級提示
*/
private void showUpdateVersionDialog() {
String updateLog = model.getChangelog();
final String apkURL = model.getInstall_url();
FileSize = model.getBinary().getFsize();
FileName = model.getName() + ".apk";
new AlertDialog.Builder(mContext) //新建彈出框
.setTitle("更新提示")
.setIcon(R.mipmap.ic_launcher)
.setMessage(updateLog.equals("") ? "暫無更新提示信息" : updateLog)
// 更新
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
down_dialog = builder.show();
Upload(apkURL);
}
})
.setNegativeButton("稍后升級", null).show();
}
開啟線程 下載APK文件
/**
* 開始下載操作
* @param apkURL 下載路徑
*/
private void Upload(final String apkURL) {
new Thread() {
@Override
public void run() {
try {
URL u = new URL(apkURL);
URLConnection conn = u.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
if (is == null) {
mHandler.sendEmptyMessage(DOWNLOAD_ERROR);
} else {
FileOutputStream fos = new FileOutputStream(Util.createFilePath(model.getName() + ".apk"));
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
downloadSize += len;
res = downloadSize * 100 / FileSize; //正在下載 下載的進度
if (res == 100) {
mHandler.sendEmptyMessage(DOWNLOAD_OK);
} else {
mHandler.sendEmptyMessage(DOWNLOAD_WORK);
}
}
is.close();
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
mHandler.sendEmptyMessage(DOWNLOAD_NOT_FILE);
}
super.run();
}
}.start();
}
處理下載時,下載后的操作
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOAD_WORK:
mPrg.setMax(FileSize);
mPrg.setProgress(downloadSize);
mPrgTx.setText("已下載" + res + "%");
break;
case DOWNLOAD_OK:
down_dialog.dismiss();
try {
File file = new File(Util.createFilePath(FileName));
Util.startActionFile(mContext, file, "application/vnd.android.package-archive");
} catch (ActivityNotFoundException E) {
Toast.makeText(mContext, "沒有合適的程序打開此文件", Toast.LENGTH_SHORT).show();
}
break;
case DOWNLOAD_ERROR:
down_dialog.dismiss();
Toast.makeText(mContext, "下載出錯", Toast.LENGTH_SHORT).show();
break;
case DOWNLOAD_NOT_FILE:
down_dialog.dismiss();
Toast.makeText(mContext, "未找到文件", Toast.LENGTH_SHORT).show();
break;
case DOWNLOAD_SHOW_DLG:
PgDialog.dismiss();
showUpdateVersionDialog();// 顯示提示對話框
break;
default:
break;
}
}
};
檢查版本更新 實際只需要兩句代碼即可
/**
* 檢查版本
*/
public void checkUpdate() {
if (Util.GetNetype(getBaseContext()) == -1) { //判斷網絡狀態
Toast.makeText(getBaseContext(), "網絡斷開了,請檢查網絡", Toast.LENGTH_SHORT).show();
} else {
DownLoad update = new DownLoad(MainActivity.this); //開始下載
update.checkVersion(Util.GET_VERSION_URL);
}
}
最后需要添加上下載文件所需要的權限(這個權限可不能忘了)
<!-- 用于進行網絡定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于訪問網絡-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 用于獲取運營商信息,用于支持提供運營商信息相關的接口 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 用于讀取手機當前的狀態 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 用于寫入緩存數據到擴展存儲卡 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
好了一個簡單的自動更新,下載文件就寫好了 。工具類里面簡單的修改就可以下載各種文件。