java – BroadcastReceiver没有收到下载完成的动作

前端之家收集整理的这篇文章主要介绍了java – 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();
        }
    }
}

这是清单:

<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

2-)添加android:exported =“true”广播接收器可以从其应用程序之外的源接收消息

3-)将意图过滤器中的动作名称更改为“android.intent.action.DOWNLOAD_COMPLETE”

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

        <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" />
 </application>

如果请求来自您的应用程序,您只收到广播,因此在您的应用程序中运行此代码,看看是否触发了接收者

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

猜你在找的Java相关文章