DownloadManager 没有收到下载完成的动作

DownloadManager doesn't receive download complete action

我有一个在后台下载文件的意图服务,注册了一个广播接收器来监听下载完成,但从未进入接收器的 onReceive() 函数。该文件似乎已完成下载,我可以在文件资源管理器中看到它,并从 DownloadManager 收到状态为 SUCCESS 的消息。就在下载成功消息之前,我收到了一个错误 Failed to chmod /mnt/internal_sd/../filedownloaded

Intent 从 main activity onCreate 开始:

Intent i = new Intent(context, MyIntentService.class);
startService(i);

意向服务:

public class MyIntentService extends IntentService  {

    DownloadManager downloadManager;

    @Override
    protected void onHandleIntent(Intent intent) {
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(downloadReceiver, filter);
        downloadFile();
    }

    void downloadFile(Uri downloadUri) {
        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(false);
        request.setTitle("My Andorid App Download");
        request.setDestinationInExternalFilesDir(getApplicationContext(), null, sku + ".apk");

        long downloadNum = downloadManager.enqueue(request);        
    }

    private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {         
            System.out.println("does not get in here.");
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            Uri u = downloadManager.getUriForDownloadedFile(id);
        }
    };
}

清单:

<service
    android:name="com.example.MyIntentService"
    android:exported="false">

    <intent-filter>
      <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />                 
    </intent-filter>

</service> 

这听起来像是权限问题,chmod 失败错误,但我不太明白是什么。

我想通了我的问题。您不应该在意图服务中使用广播接收器,因为意图服务在单独的线程上运行,它将执行您 onHandleIntent() 中的所有内容,然后消失。在下载管理器可以广播下载完成之前,我的意图服务就消失了。