Android DownloadManager

时间:2014-05-28 13:40:15

标签: android android-download-manager

我正在使用Android DownloadManager下载一些XMB文件,如果DownloadManager完成下载,则会在正常情况下发送broadcast操作android.intent.action.DOWNLOAD_COMPLETE

我的问题是,如果互联网连接丢失了。它会发送任何广播吗?如果服务器停止提供DownloadManager所做的事情,则介于两者之间。也许这是一个愚蠢的问题,我的文件非常小,所以我无法测试这种情况。

有人可以告诉我DownloadManager在这种情况下的作用吗?

2 个答案:

答案 0 :(得分:2)

广播将被发送。您需要检查DownloadManager的状态以确定它是否成功。例如:

private DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

BroadcastReceiver receiver = new BroadcastReceiver() {
    @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)) {
                    // handle data
                } else if (DownloadManager.STATUS_FAILED == c.getInt(columnIndex)) {
                    // handle error
                }
            }
        }
    }
};

有关完整示例,请参阅:this link。有关确定失败原因的方法,请参阅this link

答案 1 :(得分:0)

礼貌:Android DownloadManager Example

我仅在 DownloadManager.ACTION_DOWNLOAD_COMPLETE 广播中注册接收器。仅当下载成功完成时才调用

遵循这三个步骤

按照下面的代码片段所示创建一个BroadcastReceiver,在接收器内部,我们只需将接收到的下载ID与入队下载进行匹配,即可检查接收到的广播是否是我们的下载内容。

private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
           //Fetching the download id received with the broadcast
           long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
           //Checking if the received broadcast is for our enqueued download by matching download id
           if (downloadID == id) {
               Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
           }
       }
   };

创建了BroadcastReceiver之后,您可以在活动的onCreate方法中注册ACTION_DOWNLOAD_COMPLETE。

@Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

   }

在onDestroy中注销BroadcastReceiver也是很重要的。这样可以确保您仅在活动处于活动状态时才收听此广播

@Override
  public void onDestroy() {
      super.onDestroy();
      unregisterReceiver(onDownloadComplete);
  }

完整示例here