广播接收机未收到下载完成操作

2022-09-03 15:05:13

我正在尝试捕获下载完整事件,但我的广播接收机未收到它们。下面是接收器:

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

下面是清单:

<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>

有人看到有什么问题吗?


答案 1
  • 为您的接收器使用完整的包名称,例如com.example.DownloadListenerService
  • Add 可以从其应用程序的源接收消息。android:exported="true"BroadcastReceiveroutside
  • 将 中 的名称更改为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" />
    

仅当接收器从您的应用程序注册时,才会触发接收器 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);

答案 2

我认为 XML 中的操作名称是错误的。文档指出正确的一个是:android.intent.action.DOWNLOAD_COMPLETE不是DownloadManager.ACTION_DOWNLOAD_COMPLETE - 你需要使用常量,而不是Java形式。

<receiver android:name=".DownloadListenerService" >
    <intent-filter>
        <action android:enabled="true" android:name="android.intent.action.DOWNLOAD_COMPLETE" />
    </intent-filter>
</receiver>

推荐