1.直接通過URL下載安裝APP:
示例:
零、準備工作
0.1第三方庫
implementation ‘io.reactivex.rxjava2:rxjava:2.2.2’
implementation ‘io.reactivex.rxjava2:rxandroid:2.1.0’
implementation ‘io.reactivex.rxjava2:rxkotlin:2.3.0’
implementation ‘com.squareup.okhttp3:okhttp:3.11.0’
implementation ‘com.squareup.okio:okio:2.0.0’
0.2權限
<uses-permission android:name="android.permission.INTERNET" />
<!-- 寫入權限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
0.3格式
“Code”: 0,
“Msg”: “”,
“UpdateStatus”: 1,
“VersionCode”: 3,
“VersionName”: “1.0.2”,
“ModifyContent”: “1、優化api接口。\r\n2、添加使用demo演示。\r\n3、新增自定義更新服務API接口。\r\n4、優化更新提示界面。”,
“DownloadUrl”: “https://raw.githubusercontent.com/xuexiangjys/XUpdate/master/apk/xupdate_demo_1.0.2.apk”,
“ApkSize”: 2048
“ApkMd5”: “…” //md5值沒有的話,就無法保證apk是否完整,每次都會重新下載。
一、檢測是否是最新版本,不是則更新
private Disposable downDisposable;
private ProgressBar progressBar;
private TextView textView4;
private Button upgrade;
private long downloadLength=0;
private long contentLength=0;
private String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//判斷版本是否最新,如果不是最新版本則更新
private void test(){
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("url")
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
emitter.onError(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result="";
if (response.body()!=null) {
result=response.body().string();
}else {
//返回數據錯誤
return;
}
emitter.onNext(result);
}
});
// emitter.onNext("123");
}
}).subscribeOn(Schedulers.io())// 將被觀察者切換到子線程
.observeOn(AndroidSchedulers.mainThread())// 將觀察者切換到主線程
.subscribe(new Observer<String>() {
private Disposable mDisposable;
@Override
public void onSubscribe(Disposable d) {
mDisposable = d;
}
@Override
public void onNext(String result) {
if (result.isEmpty()){
return;
}
//2.判斷版本是否最新,如果不是最新版本則更新
String downloadUrl="https://raw.githubusercontent.com/xuexiangjys/XUpdate/master/apk/xupdate_demo_1.0.2.apk";
String title="是否升級到4.1.1版本?";
String size="新版本大小:未知";
String msg="1、優化api接口。\r\n2、添加使用demo演示。\r\n3、新增自定義更新服務API接口。\r\n4、優化更新提示界面。";
int versionCode=20000;
try {
int version = getPackageManager().
getPackageInfo(getPackageName(), 0).versionCode;
if (versionCode>version){
LayoutInflater inflater = LayoutInflater.from(TestActivity.this);
View view = inflater.inflate(R.layout.layout_dialog, null);
AlertDialog.Builder mDialog = new AlertDialog.Builder(TestActivity.this,R.style.Translucent_NoTitle);
mDialog.setView(view);
mDialog.setCancelable(true);
mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return keyCode == KeyEvent.KEYCODE_BACK;
}
});
upgrade= view.findViewById(R.id.button);
TextView textView1= view.findViewById(R.id.textView1);
TextView textView2= view.findViewById(R.id.textView2);
TextView textView3= view.findViewById(R.id.textView3);
textView4= view.findViewById(R.id.textView4);
ImageView iv_close= view.findViewById(R.id.iv_close);
progressBar= view.findViewById(R.id.progressBar);
progressBar.setMax(100);
textView1.setText(title);
textView2.setText(size);
textView3.setText(msg);
upgrade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//動態詢問是否授權
int permission = ActivityCompat.checkSelfPermission(getApplication(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(TestActivity.this, PERMISSIONS_STORAGE,
1);
}else {
upgrade.setVisibility(View.INVISIBLE);
down(downloadUrl);
}
}
});
iv_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mDialog.show();
}else {
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
mDisposable.dispose();
}
@Override
public void onError(Throwable e) {
test();
}
@Override
public void onComplete() {
}
});
}
//下載apk並更新進度條
private void down(String downloadUrl){
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
downApk(downloadUrl,emitter);
}
}).subscribeOn(Schedulers.io())// 將被觀察者切換到子線程
.observeOn(AndroidSchedulers.mainThread())// 將觀察者切換到主線程
.subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
downDisposable = d;
}
@Override
public void onNext(Integer result) {
//設置ProgressDialog 進度條進度
progressBar.setProgress(result);
textView4.setText(result+"%");
}
@Override
public void onError(Throwable e) {
Toast.makeText(getApplication(),"網絡異常!請重新下載!",Toast.LENGTH_SHORT).show();
upgrade.setEnabled(true);
}
@Override
public void onComplete() {
Toast.makeText(getApplication(),"服務器異常!請重新下載!",Toast.LENGTH_SHORT).show();
upgrade.setEnabled(true);
}
});
}
二、下載apk
//下載apk
private void downApk(String downloadUrl,ObservableEmitter<Integer> emitter){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(downloadUrl)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//下載失敗
breakpoint(downloadUrl,emitter);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.body() == null) {
//下載失敗
breakpoint(downloadUrl,emitter);
return;
}
InputStream is = null;
FileOutputStream fos = null;
byte[] buff = new byte[2048];
int len;
try {
is = response.body().byteStream();
File file = createFile();
fos = new FileOutputStream(file);
long total = response.body().contentLength();
contentLength=total;
long sum = 0;
while ((len = is.read(buff)) != -1) {
fos.write(buff,0,len);
sum+=len;
int progress = (int) (sum * 1.0f / total * 100);
//下載中,更新下載進度
emitter.onNext(progress);
downloadLength=sum;
}
fos.flush();
//4.下載完成,安裝apk
installApk(TestActivity.this,file);
} catch (Exception e) {
e.printStackTrace();
breakpoint(downloadUrl,emitter);
} finally {
try {
if (is != null)
is.close();
if (fos != null)
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
//斷點續傳
private void breakpoint(String downloadUrl,ObservableEmitter<Integer> emitter){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(downloadUrl)
.addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//下載失敗
breakpoint(downloadUrl,emitter);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.body() == null) {
//下載失敗
breakpoint(downloadUrl,emitter);
return;
}
InputStream is = null;
RandomAccessFile randomFile = null;
byte[] buff = new byte[2048];
int len;
try {
is = response.body().byteStream();
String root = Environment.getExternalStorageDirectory().getPath();
File file = new File(root,"updateDemo.apk");
randomFile = new RandomAccessFile(file, "rwd");
randomFile.seek(downloadLength);
long total = contentLength;
long sum = downloadLength;
while ((len = is.read(buff)) != -1) {
randomFile.write(buff,0,len);
sum+=len;
int progress = (int) (sum * 1.0f / total * 100);
//下載中,更新下載進度
emitter.onNext(progress);
downloadLength=sum;
}
//4.下載完成,安裝apk
installApk(TestActivity.this,file);
} catch (Exception e) {
e.printStackTrace();
breakpoint(downloadUrl,emitter);
} finally {
try {
if (is != null)
is.close();
if (randomFile != null)
randomFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
/**
路徑爲根目錄
創建文件名稱爲 updateDemo.apk
*/
private File createFile() {
String root = Environment.getExternalStorageDirectory().getPath();
File file = new File(root,"updateDemo.apk");
if (file.exists())
file.delete();
try {
file.createNewFile();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
三、安裝apk
3.1項目的src/res新建個xml文件夾再自定義一個file_paths文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="name1" path="test1" />
</paths>
1
2
3
4
3.2在清單文件中配置
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
1
2
3
4
5
6
7
8
9
3.3安裝apk
//安裝apk,包含7.0
public void installApk(Context context, File file) {
if (context == null) {
return;
}
String authority = getApplicationContext().getPackageName() + ".fileProvider";
Uri apkUri = FileProvider.getUriForFile(context, authority, file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//判讀版本是否在7.0以上
if (Build.VERSION.SDK_INT >= 24) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
//彈出安裝窗口把原程序關閉。
//避免安裝完畢點擊打開時沒反應
Process.killProcess(android.os.Process.myPid());
}
四、取消訂閱
@Override
protected void onDestroy() {
super.onDestroy();
downDisposable.dispose();//取消訂閱
}
五、自定義Dialog
5.1UI
見一、檢測是否是最新版本,不是則更新
5.2佈局
<?xml version="1.0" encoding="utf-8"?>
1
<android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/res-auto”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/lib_update_app_top_bg"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/view"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@drawable/lib_update_app_info_bg"
app:layout_constraintBottom_toTopOf="@+id/line"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView1" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="是否升級到1.0版本?"
android:textColor="@android:color/black"
android:textSize="15sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView1" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="新版本大小:"
android:textColor="#666"
android:textSize="14sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView1" />
<ScrollView
android:id="@+id/scrollView2"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1,xxxxxxxx\n2,ooooooooo"
android:textColor="#666"
android:textSize="14sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
</LinearLayout>
</ScrollView>
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:background="@drawable/textview_round_red"
android:gravity="center"
android:minHeight="40dp"
android:text="升級"
android:textColor="@android:color/white"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/scrollView2" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0%"
android:textColor="#E94339"
app:layout_constraintBottom_toTopOf="@+id/progressBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<android.support.constraint.Guideline
android:id="@+id/guideline1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<View
android:id="@+id/line"
android:layout_width="1dp"
android:layout_height="50dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:background="#d8d8d8"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
<ImageView
android:id="@+id/iv_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:src="@mipmap/lib_update_app_close"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/line" />
<android.support.constraint.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.2" />
</android.support.constraint.ConstraintLayout>
5.3其他文件
5.3.1textview_round_red.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- view背景色 -->
<solid android:color="#E94339" />
<!-- 邊框顏色 寬度 -->
<stroke
android:width="1dip"
android:color="#E94339" />
<!-- 邊框圓角 -->
<corners
android:bottomRightRadius="5dp"
android:topRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"/>
</shape >
5.3.2lib_update_app_info_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"/>
<solid android:color="@android:color/white"/>
</shape>
5.3.3styles文件
<style name="Translucent_NoTitle" parent="android:style/Theme.Dialog">
<item name="android:background">#00000000</item> <!-- 設置自定義佈局的背景透明 -->
<item name="android:windowBackground">@android:color/transparent</item> <!-- 設置window背景透明,也就是去邊框 -->
</style>
5.4圖片
版權聲明:本文爲CSDN博主「白雲飄絮」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/a896159476/article/details/84107130
2.直接通過應用市場下載安裝APP:
轉自:https://blog.csdn.net/bzlj2912009596/article/details/80589841
今天,簡單講講如何使用應用市場更新app的版本。
最近,需要做一個功能,使app能自動進行版本檢測和更新。之前,app都是使用應用市場提示用戶更新的,但是這次希望app在打開時可以自動檢測新的版本,然後進行版本更新。在網上查找了很多版本更新的資料,寫出了設計文檔。但是我的設計是讓app在內部直接下載服務器的最新版本進行更新,而領導說必須使用應用市場進行更新,所以在網上查找資料,最終解決了問題。這裏記錄一下。
app跳轉到應用市場上去更新,對開發者來說可以省很多的事。
直接看代碼:
Intent intent=new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.APP_MARKET");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
運行效果如下:
選擇對應的可以啓動應用市場。
可以在應用市場搜索相應的app,但是似乎不能滿足我們的需求,能否直接跳轉到app詳情頁面?如果該應用市場沒有我們所需的app怎麼辦?
繼續:
先掃描手機內所有的應用市場
Intent intent = new Intent();
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.APP_MARKET");
PackageManager pm = this.getPackageManager();
List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
int size = infos.size();
for (int i = 0; i < size; i++) {
ActivityInfo activityInfo = infos.get(i).activityInfo;
String packageName = activityInfo.packageName;
//獲取應用市場的包名
}
主流應用商店對應的包名如下:
包名 商店
com.android.vending Google Play
com.tencent.android.qqdownloader 應用寶
com.qihoo.appstore 360手機助手
com.baidu.appsearch 百度手機助
com.xiaomi.market 小米應用商店
com.wandoujia.phoenix2 豌豆莢
com.huawei.appmarket 華爲應用市場
com.taobao.appcenter 淘寶手機助手
com.hiapk.marketpho 安卓市場
cn.goapk.market 安智市場
點擊相應的市場跳轉到app的詳細頁面
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("market://details?id=" + "com.cailaiwang.app");//app包名
intent.setData(uri);
intent.setPackage("com.tencent.android.qqdownloader");//應用市場包名
startActivity(inent);
也可以封裝成一個函數:
/**
* 啓動到應用商店app詳情界面
*
* @param appPkg 目標App的包名
* @param marketPkg 應用商店包名 ,如果爲""則由系統彈出應用商店列表供用戶選擇,否則調轉到目標市場的應用詳情界面,某些應用商店可能會失敗
*/
public void launchAppDetail(String appPkg, String marketPkg) {
try {
if (TextUtils.isEmpty(appPkg)) return;
Uri uri = Uri.parse("market://details?id=" + appPkg);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
if (!TextUtils.isEmpty(marketPkg)) {
intent.setPackage(marketPkg);
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
簡單講講,其實很簡單,就是調用intent.addCategory("android.intent.category.APP_MARKET")可以直接跳轉到全部的應用市場,也可以使用launchAppDetail(String appPkg, String marketPkg)直接跳轉到具體的app下載界面,只需要傳入應用市場的包名和app的appId。這裏需要注意一個問題,當跳轉到具體的app界面時,需要判斷手機是否安裝了需要跳轉的應用市場,如果沒有安裝,直接跳轉回出現問題。所以跳轉前需要判斷手機是否安裝了我們需要的應用市場,如果沒有安裝,需要提示用戶安裝,然後才能進行跳轉。代碼也很簡單。
// 判斷市場是否存在的方法
public static boolean isAvilible(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();// 獲取packagemanager
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 獲取所有已安裝程序的包信息
List<String> pName = new ArrayList<String>();// 用於存儲所有已安裝程序的包名
// 從pinfo中將包名字逐一取出,壓入pName list中
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName;
pName.add(pn);
}
}
return pName.contains(packageName);// 判斷pName中是否有目標程序的包名,有TRUE,沒有FALSE
}
簡單講講,其實就是先獲取app所有安裝的包名,然後判斷是否包含我們需要的應用市場的包名。
android 使用應用市場進行版本更新就講完了。
就這麼簡單。
————————————————
轉自:
https://blog.csdn.net/bzlj2912009596/article/details/80589841
https://blog.csdn.net/a896159476/article/details/84107130