[英]How can I make an apk auto install when download completes
大家好,我想知道是否可以使用一些代码来完成下载后自动安装应用程序?
我的应用程序包含一个下载部分。 我正在使用Google云端硬盘来处理下载。 但是我在某些设备上遇到问题。 所以我决定离开Google
我现在正在使用媒体火作为主机。 我的应用程序使用直接下载。 但它始终使用下载管理器进行下载。 我想做的更像是Google云端硬盘如何直接下载。 这是给我一个下载完成后立即安装的选项。我现在用以下几行代码解决了
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new
File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
有没有一种方法可以在下载文件之前检查下载文件夹。 如果文件已经存在,请安装,如果未下载到网页上。 而是说解析错误,然后转到网页或多次下载同一文件。
一如既往地感谢您。
下载完成后即可获取下载的Uri
,因此无需指定要保存的文件名。 如果使用DownloadManager
,则下面是一个简单的示例。
final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://remotehost/your.apk"));
final long id = downloadManager.enqueue(request);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Intent installIntent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
installIntent.setDataAndType(downloadManager.getUriForDownloadedFile(id),
"application/vnd.android.package-archive");
} else {
Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(id));
try {
if (cursor != null && cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
String localUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
installIntent.setDataAndType(Uri.parse(localUri), "application/vnd.android.package-archive");
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.sendBroadcast(installIntent);
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.