Effect picture, after downloading, it will jump to the installation page
download_dialog.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="@color/colorAccent"
android:layout_gravity="center_horizontal"
android:text="版本更新"/>
<ProgressBar
android:id="@+id/mProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"/>
<TextView
android:id="@+id/mTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="@color/colorPrimary"
android:text="0%"/>
</LinearLayout >
DownloadDialog
public class DownloadDialog extends AlertDialog {
private Context mContext;
private TextView mTextView;
private ProgressBar mProgressBar;
private View view;
protected DownloadDialog(Context context) {
super(context);
this.mContext = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置对话框样式
setStyle();
//初始化控件
initView();
}
private void initView() {
view = View.inflate(mContext,R.layout.download_dialog,null);
mTextView = (TextView)view.findViewById(R.id.mTextView);
mProgressBar = (ProgressBar)view.findViewById(R.id.mProgressBar);
setContentView(view);
}
private void setStyle() {
//设置对话框不可取消
this.setCancelable(false);
//设置触摸对话框外面不可取消
this.setCanceledOnTouchOutside(false);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindow().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
//获得应用窗口大小
WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
//设置对话框居中显示
layoutParams.gravity = Gravity.CENTER;
//设置对话框宽度为屏幕的3/5
layoutParams.width = (displaymetrics.widthPixels/3)*2;
}
//设置进度条
public void setProgress(int progress){
mTextView.setText(progress+"%");
mProgressBar.setMax(100);
mProgressBar.setProgress(progress);
}
}
Configure in AndroidManifest.xml
<!-- 联网权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 读取手机状态权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 往sdcard中写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 读取sdcard中数据的权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application>
.....
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="包名.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
</application>
Configure filepaths.xml under res/xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path path="Download/" name="myDownload" />
</paths>
Current class
public class DownloadActivity extends BaseActivity {
private DownloadManager downloadManager;
private DownloadDialog downloadDialog;
String qqUrl = "http://fga0.market.xiaomi.com/download/AppStore/0e02a48306458ddc088caf86d628b6a6866402771";
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case DownloadManager.STATUS_SUCCESSFUL:
downloadDialog.setProgress(100);
canceledDialog();
Toast.makeText(DownloadActivity.this, "下载任务已经完成!", Toast.LENGTH_SHORT).show();
//调用,apkPath 入参就是 xml 中共享的路径
String apkPath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+File.separator+ "myApp.apk";
//AppUpdate.installApk(DownloadActivity.this,apkPath );
Log.d("+++++++apkPath=",apkPath+"");
File apkFile = new File(apkPath);
Log.d("+++++++apkFile=",apkFile+"");
/*Uri contentUri = FileProvider.getUriForFile(DownloadActivity.this,"com.xiang.mylianlianshou2.fileprovider",apkFile);
Log.d("+++++++contentUri=",contentUri+"");*/
//Android 7.0 系统共享文件需要通过 FileProvider 添加临时权限否则系统会抛出 FileUriExposedException .
Intent intent = new Intent(Intent.ACTION_VIEW);
//Android 7.0 系统共享文件需要通过 FileProvider 添加临时权限,否则系统会抛出 FileUriExposedException .
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(DownloadActivity.this,"com.xiang.mylianlianshou2.fileprovider",apkFile);
Log.d("+++++++contentUri=",contentUri+"");
intent.setDataAndType(contentUri,"application/vnd.android.package-archive");
}else {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(
Uri.fromFile(apkFile),
"application/vnd.android.package-archive");
}
startActivity(intent);
break;
case DownloadManager.STATUS_RUNNING://下载中
//int progress = (int) msg.obj;
downloadDialog.setProgress((int) msg.obj);
//canceledDialog();
break;
case DownloadManager.STATUS_FAILED:
canceledDialog();
break;
case DownloadManager.STATUS_PENDING:
showDialog();
break;
}
}
};
@Override
protected void initComponents() {
setContentView(R.layout.activity_download);
downLoadApk();
}
@Override
protected void initData() {
}
private void showDialog() {
if(downloadDialog==null){
downloadDialog = new DownloadDialog(this);
}
if(!downloadDialog.isShowing()){
downloadDialog.show();
}
}
private void canceledDialog() {
if(downloadDialog!=null&&downloadDialog.isShowing()){
downloadDialog.dismiss();
}
}
private void downLoadApk() {
//创建request对象
DownloadManager.Request request=new DownloadManager.Request(Uri.parse(qqUrl));
//设置什么网络情况下可以下载 DownloadManager.Request.NETWORK_WIFI
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
//设置通知栏的标题
request.setTitle("下载");
//设置通知栏的message
request.setDescription("今日头条正在下载.....");
//设置漫游状态下是否可以下载
request.setAllowedOverRoaming(false);
//设置文件存放目录
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS,"/myApp.apk");
//获取系统服务
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//进行下载
final long requestId = downloadManager.enqueue(request);
//downloadManager.remove(id);//删除下载
new Thread(){
@Override
public void run() {
super.run();
setXiaZaiDeJianTing(requestId);
}
}.start();
}
private void setXiaZaiDeJianTing(long requestId) {
DownloadManager.Query query=new DownloadManager.Query();
//根据任务编号id查询下载任务信息
query.setFilterById(requestId);
try {
boolean isGoging=true;
while (isGoging) {
Cursor cursor = downloadManager.query(query);
if (cursor != null && cursor.moveToFirst()) {
//获得下载状态
int state = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (state) {
case DownloadManager.STATUS_SUCCESSFUL://下载成功
isGoging=false;
handler.sendEmptyMessage(downloadManager.STATUS_SUCCESSFUL);//发送到主线程,更新ui
break;
case DownloadManager.STATUS_FAILED://下载失败
isGoging=false;
handler.sendEmptyMessage(downloadManager.STATUS_FAILED);//发送到主线程,更新ui
break;
case DownloadManager.STATUS_RUNNING://下载中
/*
* 计算下载下载率;*/
/* COLUMN_TOTAL_SIZE_BYTES 总大小字节*/
int totalSize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
/*COLUMN_BYTES_DOWNLOADED_SO_FAR 字节下载到目前为止*/
int currentSize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int progress = (int) (((float) currentSize) / ((float) totalSize) * 100);
Message message = new Message();
message.what=downloadManager.STATUS_RUNNING;
message.obj=progress;
handler.sendMessageAtFrontOfQueue(message);//发送到主线程,更新ui
break;
case DownloadManager.STATUS_PAUSED://下载停止
handler.sendEmptyMessage(DownloadManager.STATUS_PAUSED);
break;
case DownloadManager.STATUS_PENDING://准备下载
handler.sendEmptyMessage(DownloadManager.STATUS_PENDING);
break;
}
}
if(cursor!=null){
cursor.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}