android 下载apk后如何安装程序,Android下载并安装APK
通过DownloadManager来下载APK到本地,下载完成后收到广播再安装APK,可用在软件更新等场合。添加权限Activity源码package com.example.administrator.downloadtest;import android.app.Activity;import android.app.DownloadManager;import android.content
通过DownloadManager来下载APK到本地,下载完成后收到广播再安装APK,可用在软件更新等场合。
添加权限
Activity源码
package com.example.administrator.downloadtest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btDownload = (Button) findViewById(R.id.bt_download);
btDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
downloadApk();
}
});
/**注册下载完成广播**/
registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
/**下载APK**/
private void downloadApk() {
String apkUrl = "http://192.168.1.1/downloadtest.apk";
Uri uri = Uri.parse(apkUrl);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
// 设置允许使用的网络类型,这里是移动网络和wifi都可以
request.setAllowedNetworkTypes(request.NETWORK_MOBILE| request.NETWORK_WIFI);
//设置是否允许漫游
request.setAllowedOverRoaming(false);
//设置文件类型
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(apkUrl));
request.setMimeType(mimeString);
//在通知栏中显示
request.setNotificationVisibility(request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle("download...");
request.setVisibleInDownloadsUi(true);
//sdcard目录下的download文件夹
request.setDestinationInExternalPublicDir("/download", "downloadtest.apk");
// 将下载请求放入队列
downloadManager.enqueue(request);
}
private BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
/**下载完成后安装APK**/
installApk();
}
};
private void installApk() {
Intent i = new Intent(Intent.ACTION_VIEW);
String filePath = "/sdcard/download/downloadtest.apk";
i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
startActivity(i);
}
}
更多推荐
所有评论(0)