效果图,下载完成会跳转到安装页面

download_dialog.xml

            
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);    }}

在AndroidManifest.xml中配置

                                        .....                                

res/xml下配置filepaths.xml

    

 

当前类

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();        }    }}

 

更多相关文章

  1. Android(安卓)studio中音频播放与进度条联动
  2. Android(安卓)给View加圆角
  3. Android——Notifications笔记
  4. ch07 Android(安卓)日期与时间对话框
  5. Android实现图片缩放示例
  6. Android(安卓)设置桌面背景
  7. android定制对话框
  8. Android(安卓)Service一前台服务(四)
  9. 不让屏幕翻转扰乱你的进度对话框

随机推荐

  1. android Edittext内容字体大小动态变化
  2. android之检测手机电池
  3. android 检查gps
  4. AsyncTask(异步线程)的用法
  5. Android(安卓)UI设计小知识——渐变色背
  6. Android锁屏监听
  7. ':app:transformClassesWithDexForDebug'
  8. Android Socket网络通信
  9. Android使用SAX解析XML(4)
  10. android 手势