Android广播接收器没有呼叫

时间:2017-03-16 14:38:00

标签: android

我开发了一个使用android下载管理器和广播接收器的Android应用程序,完成下载后我将成功响应传递给BroadcastReceiver类,但是没有调用。我做错了什么?

public class MobuleDownloadManager {
    private boolean isReaname = false;
    private ProgressDialog mProgressDialog;
    private Activity activity;
    private DownloadFile mDownloadClas;
    private String TAG = "MobuleDownloadManager", URL, mFileName, mDisplayName_;
    private AlertDialog alert;

    private DownloadManager downloadManager;
    private long enqueue, id;
    SharedPreferences preferenceManager;
    final String strPref_Download_ID = "PREF_DOWNLOAD_ID";
    public static BroadcastReceiver downloadReceiver = null;
    final Timer myTimer = new Timer();
    Cursor cursorMain, cursorTimer;
    private SharedPreferences.Editor PrefEdit;
    int bytes_total;

    public MobuleDownloadManager(final Activity activity_, String mFilePath_,
                                 final String mFileName_, final String mDisplayName) {
        super();

        this.URL = mFilePath_;
          fileDownloadManager(URL);

        FileInputStream in = null;
        try {
            in = activity.openFileInput(mFileName);
            // file is alredy exist so no need too download again just open file
            myTimer.cancel();
            OnHttpResponseDownloadFile callBack = (OnHttpResponseDownloadFile) activity;
            callBack.onSuccessDownloadFile(mFileName, mDisplayName_);
            fileDownloadManager(URL);
        } catch (FileNotFoundException e1) {
            try {
                fileDownloadManager(URL);
        } 

    }
    private void fileDownloadManager(String url) {
        preferenceManager = PreferenceManager.getDefaultSharedPreferences(activity);

        downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        id = downloadManager.enqueue(request);

        mProgressDialog = new ProgressDialog(activity);
        mProgressDialog.setTitle("Downloading");
        mProgressDialog.setMessage("Downloading, Please Wait!");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                "Cancel", new DialogInterface.OnClickListener() {
                    // Set a click listener for progress dialog cancel
                    // button
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            myTimer.cancel();
                            downloadManager.remove(id);
                            mProgressDialog.dismiss();
                        } catch (Exception e) {
                            Log.e(TAG, e.toString());
                        }

                    }
                });

        mProgressDialog.show();
        PrefEdit = preferenceManager.edit();
        PrefEdit.putLong(strPref_Download_ID, id);
        PrefEdit.commit();

        myTimer.schedule(new TimerTask() {

            public void run() {
                try {
                    DownloadManager.Query q;
                    q = new DownloadManager.Query();
                    q.setFilterById(preferenceManager.getLong(strPref_Download_ID, 0));
                    cursorTimer = downloadManager.query(q);

                    if (cursorTimer.moveToFirst() && cursorTimer != null) {
                        Log.e("bytes_total", "cursorTimer");
                        int bytes_downloaded = cursorTimer.getInt(cursorTimer.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        bytes_total = cursorTimer.getInt(cursorTimer.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                        final int dl_progress = (int) ((double) bytes_downloaded / (double) bytes_total * 100f);

                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mProgressDialog.setProgress(dl_progress);
                            }
                        });

                        if (bytes_total == bytes_downloaded) {
                            Log.e(TAG, "run block 1");
                            myTimer.cancel();
                            mProgressDialog.dismiss();
                            IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
                            activity.registerReceiver(downloadReceiver, intentFilter);
                            Log.e(TAG, "run block 2");
                        }
                    } else {
                                           }

                } catch (Exception e) {
                    Log.e(TAG, "Exception:" + e.getMessage());
                } finally {
                    Log.e(TAG, "finally");
                    cursorTimer.close();
                }
            }

        }, 0, 1000);

        try {
            Log.e(TAG, "BroadcastReceiver ");
            downloadReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    Log.e(TAG, "BroadcastReceiver onReceive");
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(preferenceManager.getLong(strPref_Download_ID, 0));
                    cursorMain = downloadManager.query(query);
                    Log.e(TAG, "BroadcastReceiver " + cursorMain.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    if (cursorMain.moveToFirst()) {
                        int columnIndex = cursorMain.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        int status = cursorMain.getInt(columnIndex);

                        if (status == DownloadManager.STATUS_SUCCESSFUL) {
                            ParcelFileDescriptor file;
                            try {
                                file = downloadManager.openDownloadedFile(preferenceManager.getLong(strPref_Download_ID, 0));
                                InputStream fileStream = new FileInputStream(file.getFileDescriptor());
                                FileOutputStream newOS = null;

                                if (isReaname) {
                                    newOS = activity.openFileOutput("encrypted$" + mFileName, Context.MODE_PRIVATE);
                                } else {
                                    newOS = activity.openFileOutput(mFileName, Context.MODE_PRIVATE);
                                }
                                byte[] buffer = new byte[1024];
                                int length;
                                while ((length = fileStream.read(buffer)) > 0) {
                                    newOS.write(buffer, 0, length);
                                }

                                newOS.flush();
                                fileStream.close();
                                newOS.close();
                                downloadManager.remove(id);
                                activity.unregisterReceiver(downloadReceiver);
                                PrefEdit.clear();
                                OnHttpResponseDownloadFile callBack = (OnHttpResponseDownloadFile) activity;
                                callBack.onSuccessDownloadFile(mFileName, mDisplayName_);

                            } catch (Exception e) {

                            }
                        } else {
                            downloadManager.remove(id);
                            activity.unregisterReceiver(downloadReceiver);
                        }
                    }
                }
            };
        } catch (Exception e) {

        } finally {
        }
    }
}

声明: public static DownloadReciver downloadReceiver = new DownloadReciver();

现在这是我的reciver类

public static class DownloadReciver extends BroadcastReceiver {
        public DownloadReciver() {
            super();
        }
        @Override
        public void onReceive(Context context, Intent intent) {
        }
    }

我这样打电话:

if (bytes_total == bytes_downloaded) {
    IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    activity.registerReceiver(downloadReceiver, intentFilter);
    }

这是我的清单:

<receiver android:name="com.mobule.lms.connection.MobuleDownloadManager$DownloadReciver" >
            <intent-filter>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
        </intent-filter>
        </receiver> 

我得到了例外: java.lang.RuntimeException:无法启动接收器com.mobule.lms.connection.MobuleDownloadManager $ DownloadReciver:java.lang.NullPointerException

3 个答案:

答案 0 :(得分:0)

您是否在Manifest中声明了BroadcastReceiver?

答案 1 :(得分:0)

在Manifest中声明Receiver,检查Android 6.0 Marshmallow权限是否给定,并检查是否提供使用权限。 对于Inner Class,我们也可以在Manifest中声明: 接收器android:name属性应该看起来像.path.to.class.MyClass $ MyInnerClass

答案 2 :(得分:0)

您应该将广播接收器注册为以下

<receiver android:name=".path.to.your.downloadReciever" >
    <intent-filter>
       <action android:name="your filter" />
    </intent-filter>
</receiver>