下载管理器完成多次下载后如何执行任务
当我的应用程序启动时,我需要下载多个图像。我可以正确下载图像,但是我面临的问题是如何执行像转移到其他活动(显示图片)的任务或者在这种情况下(用于测试目的)更改文本视图的文本一次全部下载完成。在我的代码中,即使一次下载完成,它也会更改文本视图,这不是我想要的。我如何实现这一目标?下载管理器完成多次下载后如何执行任务
public class MainActivity extends ActionBarActivity {
TextView testtv;
String[] imagenames;
String BASEURL;
private long enqueue;
private DownloadManager dm = null;
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BASEURL = getResources().getString(R.string.base_URL);
imagenames = getResources().getStringArray(R.array.pic_name);
testtv = (TextView) findViewById(R.id.testtv);
File Path = getExternalFilesDir(null);
File noMedia = new File(Path + "/.nomedia");
if (!noMedia.exists()) {
try {
noMedia.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Path.mkdirs();
for (int index = 0; index < imagenames.length; index++) {
File image = new File(Path + "/" + imagenames[index]);
if (image.exists()) {
testtv.setText("file exists");
} else {
Boolean result = isDownloadManagerAvailable(getApplicationContext());
if (result) {
downloadFile(imagenames[index]);
}
}
}
}
@SuppressLint("NewApi")
public void downloadFile(String imagename) {
// TODO Auto-generated method stub
String DownloadUrl = BASEURL + imagename;
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(DownloadUrl));
request.setDescription("P3 Resources"); // appears the same
// in Notification
// bar while
// downloading
request.setTitle("P3 Resources");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
}
String fileName = DownloadUrl.substring(
DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length());
request.setDestinationInExternalFilesDir(getApplicationContext(), null,
fileName);
// get download service and enqueue file
dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
enqueue = dm.enqueue(request);
}
public static boolean isDownloadManagerAvailable(Context context) {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui",
"com.android.providers.downloads.ui.DownloadList");
List<ResolveInfo> list = context.getPackageManager()
.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
} catch (Exception e) {
return false;
}
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
testtv.setText("Download Complete");
}
}
}
}
};
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
您当前只存储从DL管理器返回的最后一个ID。将其更改为线程安全队列 - 如果我了解您的使用情况正确,应该修复此问题。
public class MainActivity extends ActionBarActivity {
TextView testtv;
String[] imagenames;
String BASEURL;
private Queue<Long> enqueue = new ConcurrentLinkedQueue<>();
private DownloadManager dm = null;
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BASEURL = getResources().getString(R.string.base_URL);
imagenames = getResources().getStringArray(R.array.pic_name);
testtv = (TextView) findViewById(R.id.testtv);
File Path = getExternalFilesDir(null);
File noMedia = new File(Path + "/.nomedia");
if (!noMedia.exists()) {
try {
noMedia.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Path.mkdirs();
for (int index = 0; index < imagenames.length; index++) {
File image = new File(Path + "/" + imagenames[index]);
if (image.exists()) {
testtv.setText("file exists");
} else {
Boolean result = isDownloadManagerAvailable(getApplicationContext());
if (result) {
downloadFile(imagenames[index]);
}
}
}
}
@SuppressLint("NewApi")
public void downloadFile(String imagename) {
// TODO Auto-generated method stub
String DownloadUrl = BASEURL + imagename;
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(DownloadUrl));
request.setDescription("P3 Resources"); // appears the same
// in Notification
// bar while
// downloading
request.setTitle("P3 Resources");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
}
String fileName = DownloadUrl.substring(
DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length());
request.setDestinationInExternalFilesDir(getApplicationContext(), null,
fileName);
// get download service and enqueue file
dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
enqueue.offer(dm.enqueue(request));
}
public static boolean isDownloadManagerAvailable(Context context) {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui",
"com.android.providers.downloads.ui.DownloadList");
List<ResolveInfo> list = context.getPackageManager()
.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
} catch (Exception e) {
return false;
}
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
if (enqueue.contains(downloadId)) {
enqueue.remove(downloadId);
}
if (!enqueue.isEmpty()) {
return;
}
//not waiting on any more downloads
testtv.setText("Downloads Complete");
}
}
};
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
谢谢@Steve Siebert.work像一个魅力 – 2014-11-04 09:59:55
np,很高兴我能帮上忙。 – 2014-11-04 10:03:18
首先,我必须说,听起来你不应该使用下载管理器。
如果你想要下载图像并显示它们,你应该使用HTTPUrlConnection或类似的方法,并且这样做。
也就是说,有几种方法可以实现你想要的。
Java期货是一种方法。 RxJava可能是一个不错的选择。
哎呀,只要将预期的结果添加到数组中,并在onReceive中迭代即可使用。
如果它只是图像..为什么不能使用http://square.github.io/picasso/? – sijeesh 2014-11-04 07:00:25