即使广播未发送,onReceive也会调用

时间:2018-04-09 21:11:11

标签: android broadcastreceiver broadcast android-broadcastreceiver

我在我的应用主要活动的onCreate()

中宣布了以下接收器

我从UpdaterService IntentService发送广播UpdaterService.BROADCAST_ACTION_STATE_CHANGE(下面的代码)。

但是,我只在UpdaterService开始后一次发送此广播,一次仅在UpdaterService之后发送一次。

问题:然而在日志消息“misrefreshing:....”中打印了3次。最后两次是可以理解的。但是第一次发送日志消息是:“misrefreshing:false”,如果您阅读代码,则会出现意外情况。

内部MainActivity#onCreate

mRefreshingReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (UpdaterService.BROADCAST_ACTION_STATE_CHANGE.equals(intent.getAction())) {
                mIsRefreshing = intent.getBooleanExtra(UpdaterService.EXTRA_REFRESHING, false);
                updateRefreshingUI();
                Log.i("haha","misrefreshing: " + mIsRefreshing);
                mPagerAdapter.notifyDataSetChanged();
            }
        }
    };

UpdaterService上课:

public class UpdaterService extends IntentService {
    private static final String TAG = "UpdaterService";

    public static final String BROADCAST_ACTION_STATE_CHANGE
        = "com.example.xyzreader.intent.action.STATE_CHANGE";
    public static final String EXTRA_REFRESHING
        = "com.example.xyzreader.intent.extra.REFRESHING";

public UpdaterService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {

    //check for network connectivity

    sendStickyBroadcast(
            new Intent(BROADCAST_ACTION_STATE_CHANGE).putExtra(EXTRA_REFRESHING, true));

    for (String category : categories) {
        try {
            JSONObject rootJson = RemoteEndpointUtil.fetchJson(category);
            if(rootJson == null) {
                sendStickyBroadcast(
                        new Intent(BROADCAST_ACTION_STATE_CHANGE).putExtra(EXTRA_REFRESHING, false));
                return;
            }

            //enter data into database... removed for Stackoverflow readability

            getContentResolver().applyBatch(ItemsContract.CONTENT_AUTHORITY, cpo);

        } catch (JSONException | RemoteException | OperationApplicationException e) {
            Log.e(TAG, "Error updating content.", e);
        }
    }

    sendStickyBroadcast(
            new Intent(BROADCAST_ACTION_STATE_CHANGE).putExtra(EXTRA_REFRESHING, false));
   }
}

0 个答案:

没有答案