簡體   English   中英

Android DownloadManager-下載並安裝APK

[英]Android DownloadManager - Download apk and install it

我到處都在尋找如何下載不是從市場上下載的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));

根據文檔,您可以指定要保存文件的位置。 您所要做的就是在將請求設置為DownloadManager之前添加此行:

request.setDestinationInExternalFilesDir (context, dirType, subPath);

您可以使用以下代碼查詢下載的本地文件:

請注意:如果下載失敗,將返回null。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM