下载完成后onReceive没有调用

时间:2016-09-06 11:19:18

标签: android android-download-manager

我正在尝试通过此tutorial使用android downloadManager。我在一个函数中移动broadCastReciever块,下面是我的代码:

public void downloadManager(){

    boolean is_downloaded = false;

        Log.e("error ", "1");
        receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.e("error ", "2");
                String action = intent.getAction();

                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                     Log.e("error ", "3");
                     DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(enqueue);
                    Cursor c = dm.query(query);
                    Log.e("error ", "4");
                    if (c.moveToFirst()) {
                        Log.e("error ", "5"); 
                        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);

                         if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                            // download finished successfully
                            is_downloaded = true;
                            Log.e("error ", "6");
                        }
                    }
                }
            }
        };

       getActivity().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

     }

当我运行项目时,is_downloaded将保持false。在logcat我可以看到这一行:

error: 1

表示应用程序控件永远不会到达其他Logs所以

@Override
public void onReceive(Context context, Intent intent)

永远不会打电话。但图像下载成功。一切似乎都好,问题出在哪里?

2 个答案:

答案 0 :(得分:1)

尝试使用 <uses-permission android:name="android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS" />

当然,不要忘记这一点:

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

如果没有帮助尝试使用BroadcastListener

public class DownloadListenerService extends BroadcastReceiver {        
    @Override
    public void onReceive(final Context context, Intent intent) {
        System.out.println("got here");
       ///// your code here
        }
    }
}

`

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

`

部分代码来自: https://stackoverflow.com/a/18789470/1979882

答案 1 :(得分:0)

通过AsyncTask尝试,在onPreExecute()中保持isDownloaded为false,然后在doInBackground()中下载内容,然后在onPostExecute()中为isDownloaded指定true。