本次主要实现的是安卓的自动更新功能,我把它放在了SpalshActivity中。 代码里会有注释。有什么不对的欢迎留言指正.。
package com.py.massiou.activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.content.FileProvider;
import android.util.Log;
import com.py.massiou.R;
import com.py.massiou.base.BaseActivity;
import com.py.massiou.base.Constants;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class SpalshActivity extends BaseActivity {
public String mLocalVersionName = "";//定义当前的APP版本号
private ProgressDialog mDialog;//下载更新的进度条提示框
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
try {
//获取软件版本号,对应AndroidManifest.xml下android:versionCode
mLocalVersionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
//这里是请求后台接口,获取服务器上传的APP版本号,然后调用checkversion方法,用本地的和后台的服务器版本做对比,如果版本不一样就提示更新
OkHttpUtils.post()
.url(Constants.BASEURL)
.addParams("type", "0")
.build().execute(new StringCallback() {
@Override
public void onError(Request request, Exception e) {}
@Override
public void onResponse(String response) {
Log.i("..SpalshActivity", "60_onResponse: " + response);
checkVersion(obj.getString("versionName"));//传入后台的版本号,对比
}
});
}
public void checkVersion(String netVersionName) {
Log.i("..SplashActivity65", "checkVersion: " + netVersionName + " == " + mLocalVersionName);
if (!mLocalVersionName.equals(netVersionName)) {
new AlertDialog.Builder(this)
.setMessage("发现新版本,需要更新")
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
loadNewVersion();
}
}).show();
} else {
}
}
private void loadNewVersion() {
String url = "http://www.baidu.com/Content/android.apk";//这里是链接文件的地址
mDialog = new ProgressDialog(SpalshActivity.this);
mDialog.setMax(100);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.show();
Log.i("..SpalshActivity", "111_loadNewVersion: ");
OkHttpUtils.get().url(url).build()
.execute(new FileCallBack(getExternalCacheDir().getAbsolutePath(), "newapp.apk") {
@Override
public void inProgress(float progress) {
//进度条的更新
mDialog.setProgress((int) (100 * progress));
}
@Override
public void onError(Request request, Exception e) {
Log.i("..MainActivity33", "onError: ");
}
@Override
public void onResponse(File response) {
//下载完毕之后走这个方法,安装应用
installAPK(SpalshActivity.this, response);
mDialog.dismiss();
}
});
}
/**
* 安装应用,兼容7.0
*/
private void installAPK(Context mContext, File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
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");
}
mContext.startActivity(intent);
}
在androidManifest清单文件中添加更新的内容提供者
xml的file_paths文件
![image.png](https://upload-images.jianshu.io/upload_images/3499890-0c864d8489fdc6b0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
以上便是此次的自动更新的代码了。当然如果你想要手动检查更新的话,比这个要简单多了。只需要点击的时候让他跳转到你下载apk的地址就可以了。
安卓8.0安装apk需要再Manifiest中添加权限
8.0安装apk的问题已解决
使用上面的调用installApk方法
@RequiresApi(api = Build.VERSION_CODES.O)
private void startInstallPermissionSettingActivity() {
//注意这个是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
startActivityForResult(intent, 10086);
}
//安装应用
private void installApk(Context mContext, File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
} else {//Android7.0之后获取uri要用contentProvider
Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getBaseContext().startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 1) {
//再次执行上面的流程,包含权限判等
loadNewVersion();
}
}