阅读量: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.INTERNET
和android.permission.WRITE_EXTERNAL_STORAGE
。