Android開發之應用更新或軟體下載
本文章學習前提:okHttp3或以上,EventBus或其它事件總線工具,四大組件的Activity和Service,安卓通知基礎知識
新建專案檔案
目錄結構如下:
MainActivity.java
獲取權限
本專案所需權限
<!-- 網路權限-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 軟體安裝權限-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- 檔案讀寫權限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Android 6.0以上并且targetSDKVersion>=23時需要動態申請權限
在MainActivity.java中創建權限申請方法
// 獲取權限方法
public static void getPermissionCamera(Activity activity) {
// 檢查權限
int readPermissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
int writePermissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
// 檢查是否有該權限,沒有才去申請
// PackageManager.PERMISSION_GRANTED--->有
// PackageManager.PERMISSION_DENIED---->無
if (readPermissionCheck != PackageManager.PERMISSION_GRANTED|| writePermissionCheck != PackageManager.PERMISSION_GRANTED) {
// 將這些權限添加到陣列中
String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
// 通過ActivityCompat.requestPermissions()方法申請權限
ActivityCompat.requestPermissions(
activity,
permissions,
0);
}
}
在權限中,有兩種不同的大類,運行時權限和非運行時權限
運行時權限是軟體正常運行時需要用到的權限如果沒有會影響軟體功能或報錯,運行時權限的申請就需要用到以上方法,
非運行時權限是指軟體運行程序中并不需要該權限是為了某些特殊的功能,如軟體安裝等需要申請的權限,即便沒有也不影響軟體的正常運行,我們需要在下載完成后點擊安裝跳轉到軟體安裝頁面,所以我們需要申請的軟體安裝權限就需要用到以下方法
public void checkPermission(){
boolean haveInstallPermission;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
haveInstallPermission = getPackageManager().canRequestPackageInstalls();
if(!haveInstallPermission){
//沒有權限讓調到設定頁面進行開啟權限;
Uri packageURI = Uri.parse("package:" + getPackageName());
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
startActivityForResult(intent, 10086);
}else{
//有權限,執行自己的邏輯;
}
}else{
//其他android版本,可以直接執行安裝邏輯;
}
}
跳轉到設定頁面讓用戶自行打開軟體安裝權限
版本對比
Global.LOCAL_VERSION<Global.SERVICE_VERSION
本地版本低于服務端版本就創建更新彈窗
創建更新彈窗
當你的本地版本低于你獲取到的服務端版本號,就需要彈出彈窗確保軟體的及時跟新
private void checkVersion() {
if (Global.LOCAL_VERSION<Global.SERVICE_VERSION) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("軟體更新通知")
.setMessage("發現新版本,建議立即跟新")
//設定更新和取消事件監聽
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(MainActivity.this, UpdateService.class);
intent.putExtra("titleId", R.string.app_name);
startService(intent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialog.create().show();
} else {
}
啟動服務
Intent intent = new Intent(MainActivity.this, UpdateService.class);
intent.putExtra("titleId", R.string.app_name);
startService(intent);
這是一段啟動服務的代碼,需要在點擊更新時啟動跟新服務,并且前臺不影響用戶的正常體驗
Global.java
本地版本和服務端版本資訊
創建兩個靜態變數,用于MainActivity中進行版本對比
public static int LOCAL_VERSION = 0;
public static int SERVICE_VERSION = 0;
UpdateService.java
變數和常量的創建
創建如下變數和常量
// 成功和失敗的回傳碼
public static final Integer SUCCESS = 0x10000;
public static final Integer FAILED = 0x10001;
// 軟體下載鏈接,這是微信的
private static String url = "https://2077c844f4695d651cc0e04b96185f7c.rdt.tfogc.com:49156/dldir1.qq.com/weixin/android/weixin8030android2260_arm64.apk?mkey=6371c668beb5da42f221b7fc132b742a&arrive_key=257598248064&cip=218.204.114.205&proto=https";
// 軟體的最大值和當前已經下載的值
private int maxSize = 100;
private int currentSize = 0;
// 通知管理器
private NotificationManagerCompat nManager = null;
// 通知
private NotificationCompat.Builder build = null;
// 檔案名
private String s1 = "";
// 具體的檔案路徑
private String filepath = "";
// 進度
private long progress = 0;
重寫方法
繼承Service重寫onCreate、onDestroy、onStartCommand這三個方法
創建通知
在onCreate和onDestroy方法中注冊和注銷EventBus
//注冊EventBus
@Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
//注銷EventBus
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
網路請求
在onStartCommand方法中創建一個新的執行緒用于進行網路請求
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
// 開啟執行緒進行網路請求
new Thread(new Runnable() {
@Override
public void run() {
try {
fileLoad(url);
} catch (IOException e) {
// 失敗發送失敗訊息
EventBus.getDefault().post(FAILED);
e.printStackTrace();
}
}
}).start();
// 創建通知
createNotification();
return super.onStartCommand(intent, flags, startId);
}
檔案下載
創建fileLoad方法用于下載檔案并發送進度
//檔案下載方法
private void fileLoad(String url) throws IOException {
// 創建檔案輸出流
FileOutputStream fileOutputStream = null;
// okHttp發起網路請求并回傳結果
OkHttpClient ok = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url(url)
.build();
Call call = ok.newCall(request);
// 獲取到回傳體
ResponseBody body = call.execute().body();
// 斷言,如果回傳題不為空繼續執行
assert body != null;
// 獲取到檔案總大小
long l = body.contentLength();
// 將回傳提轉換成流
InputStream inputStream = body.byteStream();
// 通過transitionBit方法把b轉換為mb設定為最大值
maxSize = transitionBit(l);
// 創建檔案路徑目錄,通過Environment.getExternalStorageDirectory()獲取到手機檔案的根目錄
File dir = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!dir.exists()) {
dir.mkdirs();
}
// 從url中獲取檔案名方法StringReverse,反轉第一遍
String s = StringReverse(url);
int i = s.indexOf("?");
i += 1;
int i1 = s.indexOf("/");
String substring = s.substring(i, i1);
// 從url中獲取檔案名方法StringReverse,反轉回來
s1 = StringReverse(substring);
// 創建檔案
File file = new File(dir, s1);
if (!file.exists()) {
dir.createNewFile();
}
// 檔案寫入操作
byte[] buf = new byte[1024];
int len = 0;
int a = 1024 * 1024;
fileOutputStream = new FileOutputStream(file);
while ((len = inputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 0, len);
progress += len;
if (progress % a == 0) {
currentSize = transitionBit(progress);
// 每下載成功1mb通知一次,保證通知不頻繁
EventBus.getDefault().post(currentSize);
}
}
// 開了就要關
inputStream.close();
fileOutputStream.close();
filepath = Environment.getExternalStorageDirectory() + "/Download/" + s1;
EventBus.getDefault().post(SUCCESS);
}
事件監聽
創建一個方法,方法名自定義,引數型別為你通過EventBus發送的型別,用于獲取進度和改變通知的進度條百分比
// 創建EventBus監聽
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void UpdateEventBus(Integer message) {
// 轉換百分比,不先除再乘的原因是int小于1會轉換0
int a = currentSize * 100;
int b = a / maxSize;
// 設定notification的內容,每次通過EventBus監聽到資料時都去改變百分比
build.setContentText("下載中:" + b + "%");
// 設定進度條,進度條無需改變引數
build.setProgress(maxSize, currentSize, false);
// 發送通知
nManager.notify(1, build.build());
// 當檔案下載完成后
if (message == SUCCESS) {
Intent install = StartInstall();
PendingIntent intent = PendingIntent.getActivity(this, 0, install, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID")
.setSmallIcon(R.drawable.ic_baseline_arrow_drop_down_circle_24)
.setContentTitle("下載完成")
.setContentText("點擊安裝")
.setContentIntent(intent);
nManager.cancel(1);
nManager.notify(2, builder.build());
}
if (message == FAILED) {
Toast.makeText(this, "軟體更新失敗", Toast.LENGTH_SHORT).show();
}
}
位元組轉換
在檔案下載的寫入環節有一個currentSize = transitionBit(progress);這個方法是將單位為b的轉換成mb,用于獲取人們普遍認知的檔案大小
// b轉mb
private Integer transitionBit(long b) {
long l = b / 1024;
long l1 = l / 1024;
return Math.toIntExact(l1);
}
單位的轉換基本規則如下:
1B(位元組)=8b(位)
1 KB = 1024 B
1 MB = 1024 KB
1 GB = 1024 MB
1TB = 1024GB
所以b轉成mb只需要乘上兩個1024即可
字串反轉
在檔案下載設定檔案安裝包名稱的時候我遇到了一個難題,微信的下載鏈接中安裝包名即不在最后又不在最前,所以我通過反轉后進行字符的截取操作,然后再反轉一便就是安裝包的名稱了
// 字串反轉
private String StringReverse(String str) {
StringBuffer stringBuffer = new StringBuffer(str);
String s = stringBuffer.reverse().toString();
return s;
}
安裝程式
當我們完成了檔案的下載后,再事件監聽中會銷毀進度條的通知創建一個下載完成安裝通知,我們通過通知的setContentIntent(intent);設定安裝程式,安裝程式我們封裝成一個方法
// 安裝程式
public Intent StartInstall() {
Intent install = new Intent(Intent.ACTION_VIEW);
// 設定FLAG_ACTIVITY_NEW_TASK,確保軟體安裝后回傳該頁面
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 臨時訪問讀權限 設定FLAG_GRANT_READ_URI_PERMISSION,intent的接受者將被授予 INTENT資料uri或者在ClipData上的讀權限,
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// 安卓官方更推薦使用 FileProvider.getUriForFile來獲取檔案的uri
// 要使用FileProvider需要在AndroidManifest檔案中申明,authority引數需要與AndroidManifest檔案宣告的provider標簽一致
Uri uri = FileProvider.getUriForFile(this, "com.example.android_study.fileprovider", new File(filepath));
install.setDataAndType(uri, "application/vnd.android.package-archive");
// 將設定好的intent回傳
return install;
}
install.setDataAndType中傳入的第二個引數是安裝apk所必需的,具體檔案型別對比表如下
// install取設定屬于和型別,資料就是獲取到的uri,更具檔案型別不同,type引數也不相同,具體參考下表
/*{后綴名,MIME型別}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prop", "text/plain"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"},*/
// 不知道什么型別也可以用 {"","*/*"}
每種檔案型別對應不同的字串,
SmartApplication.java
獲取本地版本和設定服務端版本
在SmartApplication中我們只需要做的就是從服務端獲取版本set到SERVICE_VERSION中了,獲取本地版本資訊set到LOCAL_VERSION版本中,這里我就不寫網路請求了,直接設定,SmartApplication要繼承Application
public void initGlobal(){
try {
Global.LOCAL_VERSION = getPackageManager().getPackageInfo(getPackageName(),0).versionCode;
Global.SERVICE_VERSION = 1;
}catch (Exception ex){
ex.printStackTrace();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_study"
android:versionCode="1"
android:versionName="1.0">
<!-- 設定版本號,每個新版本都要手動修改然后再讓用戶跟新-->
<!-- 也可以不設定,其實在build.gradle里面有,這里我是看別人寫了-->
權限注冊
<!-- 網路權限-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 軟體安裝權限-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- 檔案讀寫權限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Service注冊,Service和Activity一樣也是需要注冊到清單檔案中才能使用
<service
android:name=".common.update.UpdateService"
android:enabled="true"
android:exported="true"></service>
在application檔案中需要注冊provider,檔案的安裝需要這個標簽
<!-- 宣告provider標簽-->
<!-- authorities前面是你的專案包名 package="com.example.android_study",最夠一個是fileprovider-->
<!-- exported,是否開啟跨應用共享資料,默認false-->
<!-- grantUriPermissions 是否授予uri權限,默認false,我們選擇true-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.android_study.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<!-- meta-data -->
<!-- name選擇android.support.FILE_PROVIDER_PATHS提供檔案路徑-->
<!-- resource選擇提供檔案路徑的檔案,這邊新建在xml下,檔案名隨便取-->
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml
在資源目錄xml檔案夾下創建file_paths.xml檔案
<?xml version="1.0" encoding="utf-8"?>
<paths>
<!-- 外部路徑-->
<external-path
name="external"
path="." />
<!-- 外部檔案路徑-->
<external-files-path
name="external_files"
path="." />
<!-- 隱藏路徑-->
<cache-path
name="cache"
path="." />
<!-- 外部隱藏路徑-->
<external-cache-path
name="external_cache"
path="." />
<!-- 最主要的是files-path和root-path,其它可寫可不寫-->
<!-- 檔案路徑-->
<files-path
name="files"
path="." />
<!-- 根目錄-->
<root-path
name="root_path"
path="." />
</paths>
專案github下載地址
2002310/Androidstudy (github.com)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536156.html
標籤:Android