java - BroadcastReceiver 未收到下载完成操作

标签 java android broadcastreceiver

我正在 try catch 下载完成事件,但我的 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();
        }
    }
}

这是 list :

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

有人看到哪里出了问题吗?

最佳答案

  • 为您的接收器使用完整的包名称,例如 com.example.DownloadListenerService
  • 添加 android:exported="true" BroadcastReceiver 可以从其应用程序外部的来源接收消息。
  • intent-filter 中的 Action 的名称更改为 android.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);

关于java - BroadcastReceiver 未收到下载完成操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18789246/

相关文章:

java - 图像对话框事件

java - 如果从 jar 运行,带有嵌入式 jetty 的 Spring 应用程序找不到 webdefault.xml

Android 按钮 onclick 覆盖

android - 如何找到 View 的默认 Android 资源(例如可绘制等)

android - ClassCastException 和无法在 Android 上实例化 Activity

java - haddler 中的语音识别器似乎每次都重新打开 Activity

java - JFXTextField 不适用于 JxBrowser

java - EditText OnClickListener 需要两次点击才能工作

android - 仅当您显式调用 finish() 时才会调用 onDestroy 吗?或者有什么异常(exception)吗?

android - 使用 intent 和 BroadcastReceiver 获取 android 电池电量时的奇怪行为