android

android下载文件功能怎么实现

小亿
153
2024-05-28 10:03:12
栏目: 编程语言

在Android中实现下载文件功能通常需要使用DownloadManager类。以下是一个简单的示例代码,演示如何使用DownloadManager来下载文件:

public class MainActivity extends AppCompatActivity {

    private DownloadManager downloadManager;
    private long downloadID;

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

        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        Uri uri = Uri.parse("http://example.com/file.txt");

        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "file.txt");

        downloadID = downloadManager.enqueue(request);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(onDownloadComplete);
    }

    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (id == downloadID) {
                // 下载完成后的处理逻辑
                Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
}

在上面的示例代码中,我们首先通过DownloadManager类创建一个用于下载文件的Request对象,然后调用enqueue方法开始下载。在下载完成后,我们使用BroadcastReceiver监听DownloadManager.ACTION_DOWNLOAD_COMPLETE广播,并在接收到该广播时处理下载完成后的逻辑。

请注意,为了使下载功能正常工作,您需要在AndroidManifest.xml文件中声明权限android.permission.INTERNETandroid.permission.WRITE_EXTERNAL_STORAGE

0
看了该问题的人还看了