android下载文件功能怎么实现

508
2024/6/13 10:03:12
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: android adapter的作用是什么