Search code examples
androidbroadcastreceiverandroid-download-manager

DownloadManager doesn't receive download complete action


I have an intent service that downloads a file in the background, a broadcast receiver is registered to listen for the download completion, but never gets in the onReceive() function of the receiver. The file seems to finish downloading, I can see it in the file explorer, and get a message from the DownloadManager with status SUCCESS. Right before the download success message I'm getting an error Failed to chmod /mnt/internal_sd/../filedownloaded

Intent started from main activity onCreate:

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

Intent service:

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

manifest:

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

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

</service> 

It sounds like a permissions issue with the failed to chmod error, but I can't quite figure out what.


Solution

  • I figured out my problem. You shouldn't have a broadcast receiver in an intent service, since the intent service runs on a separate thread it will execute everything in your onHandleIntent() then go away. My intent service was gone before the download manager could broadcast the download completion.