2014-11-04 59 views
0

當我的應用程序啓動時,我需要下載多個圖像。我可以正確下載圖像,但是我面臨的問題是如何執行像轉移到其他活動(顯示圖片)的任務或者在這種情況下(用於測試目的)更改文本視圖的文本一次全部下載完成。在我的代碼中,即使一次下載完成,它也會更改文本視圖,這不是我想要的。我如何實現這一目標?下載管理器完成多次下載後如何執行任務

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)); 
} 
} 
+0

如果它只是圖像..爲什麼不能使用http://square.github.io/picasso/? – sijeesh 2014-11-04 07:00:25

回答

1

您當前只存儲從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)); 
} 
} 
+0

謝謝@Steve Siebert.work像一個魅力 – 2014-11-04 09:59:55

+0

np,很高興我能幫上忙。 – 2014-11-04 10:03:18

0

首先,我必須說,聽起來你不應該使用下載管理器。

如果你想要下載圖像並顯示它們,你應該使用HTTPUrlConnection或類似的方法,並且這樣做。

也就是說,有幾種方法可以實現你想要的。

Java期貨是一種方法。 RxJava可能是一個不錯的選擇。

哎呀,只要將預期的結果添加到數組中,並在onReceive中迭代即可使用。