我需要在私有应用程序存储中下载文件。由于Androids下载管理器无法做到这一点,我使用的是这个库:
https://github.com/novoda/download-manager
我可以开始下载,但下载完成后我不会收到广播。有没有人使用过此库并可以提供帮助。
这就是我现在发送听众的方式:
private void setupDownloadingExample() {
Uri uri = Uri.parse(BIG_FILE);
final Request request = new Request(uri)
.setDestinationInInternalFilesDir(Environment.DIRECTORY_MOVIES, "penguins.dat")
.setNotificationVisibility(NotificationVisibility.ACTIVE_OR_COMPLETE)
.setTitle("Family of Penguins")
.setDescription("These are not the beards you're looking for")
.setBigPictureUrl(PENGUINS_IMAGE);
findViewById(R.id.main_download_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(@NonNull View v) {
onComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_SHORT).show();
}
};
(MainActivity.this).registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadManager.enqueue(request);
}
});
}
代码段来自库提供的示例。
答案 0 :(得分:0)
从回购中的演示中,您需要使用广播接收器来收听下载事件:
https://github.com/novoda/download-manager/tree/master/demo-extended
在您的清单中注册如下:
<receiver
android:name="com.novoda.downloadmanager.demo.extended.DownloadBatchStartedReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.novoda.downloadmanager.action.BATCH_FIRST_TIME_START" />
</intent-filter>
</receiver>
然后你可以听完下载完成:
public class DownloadBatchCompletionReceiver extends BroadcastReceiver {
private static final int UNKNOWN_BATCH_ID = -1;
private static final String TAG = DownloadBatchCompletionReceiver.class.getSimpleName();
@Override
public void onReceive(@NonNull Context context, @NonNull Intent intent) {
long batchId = intent.getLongExtra(DownloadManager.EXTRA_BATCH_ID, UNKNOWN_BATCH_ID);
Toast.makeText(context, "Batch completed with id: " + batchId, Toast.LENGTH_SHORT).show();
Log.d(TAG, "Batch completed: " + batchId);
}
}
所有下载都被视为批量处理,即使它只下载了1个文件。