Android 如何在我的 SD 卡文件夹中下载文件

How to download file in my SD card folder in Android

我想从服务器下载文件,为此我使用这个 : https://github.com/ayz4sci/DownloadProgress ,并编写以下代码:

public class MainActivity extends AppCompatActivity implements DownloadProgressView.DownloadStatusListener {

    private Button downloadButton, playButton;
    private long downloadID;
    private String downloadURL = "http://cld8.cdn.p30download.com/p30dl-mobile/AppMgr.Pro.III.v4.00.Patched_p30download.com.apk";
    private DownloadManager downloadManager;
    private DownloadProgressView downloadProgressView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        playButton = (Button) findViewById(R.id.playButton);

        final File myDirectory = new File(Environment.getExternalStorageDirectory(), "dirName");

        if(!myDirectory.exists()) {
            myDirectory.mkdirs();
        }

        downloadProgressView = (DownloadProgressView) findViewById(R.id.downloadProgressView);
        downloadButton = (Button) findViewById(R.id.downloadButton);
        downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadURL));
                request.setTitle("You garrit");
                request.setDescription("DownloadProgress sample");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalFilesDir(getApplicationContext(), "myCustomFolderName", "p30download.com.apk");
                request.allowScanningByMediaScanner();

                downloadID = downloadManager.enqueue(request);
                downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
                    @Override
                    public void downloadFailed(int reason) {

                    }

                    @Override
                    public void downloadSuccessful() {

                        playButton.setVisibility(View.VISIBLE);
                        playButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setDataAndType(Uri.fromFile(getFileUri()), "apk/*");
                                startActivity(intent);
                            }
                        });
                    }

                    @Override
                    public void downloadCancelled() {
                        downloadButton.setVisibility(View.VISIBLE);
                    }
                });
                downloadButton.setVisibility(View.GONE);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public File getFileUri() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadID);
        Cursor cur = downloadManager.query(query);

        if (cur.moveToFirst()) {
            int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) {
                String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                return new File(Uri.parse(uriString).getPath());
            }
        }

        return null;
    }

    @Override
    public void downloadFailed(int reason) {
        System.err.println("Failed :" + reason);
        downloadButton.setVisibility(View.VISIBLE);
    }

    @Override
    public void downloadSuccessful() {
        playButton.setVisibility(View.VISIBLE);
    }

    @Override
    public void downloadCancelled() {
        downloadButton.setVisibility(View.VISIBLE);
    }
}

我想下载成功后,将这个文件保存到我的文件夹中。对于这项工作,我使用此代码:

request.setDestinationInExternalFilesDir(getApplicationContext(), "myCustomFolderName", "p30download.com.apk");

但是下载完成后,我无法在 SD 卡中显示 myCustomFolder 名称,而且我不知道我下载的文件保存在哪里!

我该如何解决这个问题?请帮助我,谢谢所有 <3

开始下载之前,尝试使用 mkdirs 创建文件夹。

File file = new File(String path)
file.mkDirs();

mkDirs() 是布尔值,因此您可以检查它是否正确创建了文件夹。

使用ion android库非常简单易用

下载文件的示例代码是

Ion.with(context)
.load("http://example.com/really-big-file.zip")
// have a ProgressBar get updated automatically with the percent
.progressBar(progressBar)
// and a ProgressDialog
.progressDialog(progressDialog)
// can also use a custom callback
.progress(new ProgressCallback() {@Override
   public void onProgress(long downloaded, long total) {
       System.out.println("" + downloaded + " / " + total);
   }
})
.write(new File("/sdcard/really-big-file.zip"))
.setCallback(new FutureCallback<File>() {
   @Override
    public void onCompleted(Exception e, File file) {
        // download done...
        // do stuff with the File or error
    }
});

不要忘记添加所需的权限。希望这有帮助:)

在下载的 onCLick 中使用以下代码

  File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File (sdCard.getAbsolutePath() + "/myCustomFolderName");
                dir.mkdirs();
                File file = new File(dir, "you_garrit.mp4");
                Uri uri = Uri.fromFile(file);

                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadURL));
                request.setTitle("You garrit");
                request.setDescription("DownloadProgress sample");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationUri(uri);
                request.allowScanningByMediaScanner();

                downloadID = downloadManager.enqueue(request);
                downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
                    @Override
                    public void downloadFailed(int reason) {
                        Log.d(TAG, "downloadFailed" + reason);
                    }

                    @Override
                    public void downloadSuccessful() {
                        Log.d(TAG, "downloadSuccessful");
                    }

                    @Override
                    public void downloadCancelled() {
                      Log.d(TAG, "downloadCancelled");
                    }
                });
                downloadButton.setVisibility(View.GONE);

如果这些对您不起作用,请告诉我