Android 版本更新下载自动安装APK,并解决Android6.0安装失败的问题
public class UpdataService extends Service {
/**
* 安卓系统下载类
**/
private DownloadManager manager;
/**
* 接收下载完的广播
**/
private DownloadCompleteReceiver receiver;
private String url;
private String DOWNLOADPATH = "/apk/";//下载路径,如果不定义自己的路径,6.0的手机不自动安装
/**
* 初始化下载器
**/
private void initDownManager() {
manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
receiver = new DownloadCompleteReceiver();
//设置下载地址
down = new ((url));
// 设置允许使用的网络类型,这里是移动网络和wifi都可以
(.NETWORK_MOBILE
| .NETWORK_WIFI);
(false);
MimeTypeMap mimeTypeMap = ();
String mimeString = ((url));
(mimeString);
// 下载时,通知栏显示途中
(.VISIBILITY_VISIBLE);
// 显示下载界面
(true);
// 设置下载后文件存放的位置
(DOWNLOADPATH, "");
("member");
// 将下载请求放入队列
(down);
//注册下载广播
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
url = ("url");
String path = ().getAbsolutePath() +DOWNLOADPATH+ "";
File file = new File(path);
if (()) {
();
}
try {
// 调用下载
initDownManager();
} catch (Exception e) {
();
(getApplicationContext(), "下载失败", Toast.LENGTH_SHORT).show();
}
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
if (receiver != null)
// 注销下载广播
unregisterReceiver(receiver);
super.onDestroy();
}
// 接受下载完成后的intent
class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//判断是否下载完成的广播
if (().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
//获取下载的文件id
long downId = (DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if ((downId) != null) {
//自动安装apk
installAPK((downId), context);
//installAPK(context);
} else {
(context, "下载失败", Toast.LENGTH_SHORT).show();
}
//停止服务并关闭广播
UpdataService.this.stopSelf();
}
}
private void installAPK(Uri apk, Context context) {
if (.SDK_INT < 23) {
Intent intents = new Intent();
("");
("");
("application/-archive");
(apk);
(apk, "application/-archive");
(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
} else {
File file = new File(().getAbsolutePath() +DOWNLOADPATH+ "");
if (()) {
openFile(file, context);
}
}
}
private void installAPK(Context context) {
File file = new File(().getAbsolutePath() +DOWNLOADPATH+ "");
if (()) {
openFile(file, context);
} else {
(context, "下载失败", Toast.LENGTH_SHORT).show();
}
}
}
public void openFile(File file, Context context) {
Intent intent = new Intent();
(268435456);
("");
String type = getMIMEType(file);
((file), type);
try {
(intent);
} catch (Exception var5) {
();
(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
}
}
public String getMIMEType(File var0) {
String var1 = "";
String var2 = ();
String var3 = ((".") + 1, ()).toLowerCase();
var1 = ().getMimeTypeFromExtension(var3);
return var1;
}
}