BroadcastReceiver没有收到下载完成动作

Joh*_*rts 14 java android broadcastreceiver

我试图捕获下载完成事件,但我的BroadcastReceiver没有收到它们.这是接收器:

public class DownloadListenerService extends BroadcastReceiver {        
    @Override
    public void onReceive(final Context context, Intent intent) {
        System.out.println("got here");
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = settings.edit();

        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            String downloadPath = intent.getStringExtra(DownloadManager.COLUMN_URI);
            editor.putString("downloadPath", downloadPath);
            editor.commit();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是清单:

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

    <receiver 
        android:name="com.example.alreadydownloaded.DownloadListenerService" 
        android:exported="true">
        <intent-filter>
            <action android:enabled="true" android:name="android.intent.action.DOWNLOAD_COMPLETE" />
        </intent-filter>
    </receiver>
 </application>
Run Code Online (Sandbox Code Playgroud)

有谁看到了什么问题?

Sim*_*mon 16

  • 为您的接收器使用完整的包名称 com.example.DownloadListenerService
  • 添加android:exported="true" BroadcastReceiver可以outside从其应用程序源接收消息.
  • 更改的名称Actionintent-filterandroid.intent.action.DOWNLOAD_COMPLETE

        <receiver 
            android:name="com.example.DownloadListenerService"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
            </intent-filter>
        </receiver>
        <uses-permission android:name="android.permission.INTERNET" />
    
    Run Code Online (Sandbox Code Playgroud)

只有在您的应用程序使用注册时才会触发接收器 registerReceiver(@Nullable BroadcastReceiver receiver,IntentFilter filter);

入队代码下载:

DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://www.google.com/images/srpr/logo4w.png"));
dm.enqueue(request);
Run Code Online (Sandbox Code Playgroud)