在Android中實現(xiàn)下載文件功能通常需要使用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
類創(chuàng)建一個用于下載文件的Request
對象,然后調(diào)用enqueue
方法開始下載。在下載完成后,我們使用BroadcastReceiver
監(jiān)聽DownloadManager.ACTION_DOWNLOAD_COMPLETE
廣播,并在接收到該廣播時處理下載完成后的邏輯。
請注意,為了使下載功能正常工作,您需要在AndroidManifest.xml文件中聲明權(quán)限android.permission.INTERNET
和android.permission.WRITE_EXTERNAL_STORAGE
。