Android DownloadManager - 下载apk并安装它

时间:2015-03-14 14:31:34

标签: java android android-intent download android-download-manager

我到处寻找如何下载不是来自市场的APK。 APK存储在我的服务器中。 所有样本都不起作用。

我希望我的应用程序为我的服务器下载APK并提示用户安装它。

到目前为止,我设法将apk下载到用户sd上。但是我无法找到它保存的路径并安装它。

private void downloadAPK() {
    String url="https://www.example.com/app.apk”;
    downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    request = new Request(Uri.parse(url));
    request.setTitle(“My App“);
    enqueue = downloadManager.enqueue(request);


      new Thread(new Runnable() {

        @Override
        public void run() {

            boolean downloading = true;

            while (downloading) {

                try {
                    Thread.sleep(10000);
                     DownloadManager.Query q = new DownloadManager.Query();
                        q.setFilterById(enqueue);

                        Cursor cursor = downloadManager.query(q);
                        cursor.moveToFirst();
                        int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                        if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                            downloading = false;
                        }

                        final int dl_progress = (int) ((double)bytes_downloaded / (double)bytes_total * 100f);

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                                Log.d("Prog", Integer.toString(dl_progress));
                            }
                        });


                        cursor.close();
                } catch (InterruptedException e) {

                }

            }

        }
    }).start();
}}


BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();


        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
             Log.w(“”, “Downloaded”)

        }
        else {
            //do something here
       }

    }
};


onCreate ...
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

2 个答案:

答案 0 :(得分:1)

根据documentation,您可以指定要保存文件的位置。您只需在将请求设置为de DownloadManager之前添加此行:

request.setDestinationInExternalFilesDir (context, dirType, subPath);

答案 1 :(得分:1)

您可以使用以下代码查询下载本地文件:

请注意: 如果下载失败,将返回null。

String path = Uri.parse(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))).getPath()