您是否必须在Android应用程序中取消注册IntentService Broadcast接收器

时间:2017-01-24 12:23:52

标签: android intentservice android-broadcastreceiver

我当前的Android应用程序使用IntentService来调用SOAP WebService。

IntentService通过LocalBroadcastManager方法中的onHandleIntent()将SOAP响应数据返回给调用活动

final Intent localIntent = new Intent(FASTEST_BROADCAST_ACTION);
localIntent.putExtra(FASTEST_EXTENDED_DATA, xmlUtility.getFastestServiceId());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(localIntent);

我的调用活动在onResume()方法

中按如下方式注册广播监听器
@Override
protected void onResume() {
        super.onResume();

        mDepartureBroadcastReceiver = new DepartureBroadcastReceiver();
        final IntentFilter statusIntentFilter = new IntentFilter(FASTEST_BROADCAST_ACTION);
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mDepartureBroadcastReceiver, statusIntentFilter);
        Log.v(LOG_TAG, "Register receiver = " + mDepartureBroadcastReceiver);

    }

一切正常,调用Web服务并将所需的响应数据返回给我的活动。

当我离开当前活动并尝试拨打unregisterReceiver

时,问题就出现了

我的onPause方法中包含此代码: -

   /**
     * Dispatch onPause() to fragments.
     */
    @Override
    protected void onPause() {
        super.onPause();

        if (mDepartureBroadcastReceiver == null) {
            //INTENTIONALLY LEFT BLANK
        } else {
            try {
                Log.v(LOG_TAG, "About to unregister receiver");
                unregisterReceiver(mDepartureBroadcastReceiver);
                Log.v(LOG_TAG, "Successfully unregistered receiver");
            } catch (final Exception exception) {
                Log.e(LOG_TAG, "Failed unregistered receiver", exception);
            } finally {
                mDepartureBroadcastReceiver = null;
            }
        }
    }

我总是得到这个例外: -

Failed unregistered receiver java.lang.IllegalArgumentException: Receiver not registered

接收人注册: -

注册收件人= com.aaa.bbb.departure.DepartureBroadcastReceiver@2879575

匹配例外: -

java.lang.IllegalArgumentException: Receiver not registered: com.aaa.bbb.departure.DepartureBroadcastReceiver@2879575

为什么会发生此异常?

为什么我不能注销这个接收器?

是否由于我的IntentService完成(例如调用其onDestroy()方法)而在我取消注册之前?

1 个答案:

答案 0 :(得分:1)

您没有使用LocalBroadcastManager取消注册。

您需要使用此LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mDepartureBroadcastReceiver);