OnReceive() method auto triggered

时间:2016-03-02 10:56:52

标签: android broadcastreceiver

I have created the one receiver inside an Activity for when internet is connected auto calling web service.

Code like

//Create receiver for while network will come auto call webservice

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        if (!noConnectivity) {
            bar.setVisibility(View.VISIBLE);
            callAuthorizeWebservice();
        } else {
            bar.setVisibility(View.INVISIBLE);
            Toast.makeText(SplashScreenActivity.this, "Check Your Internet connection", Toast.LENGTH_LONG).show();
        }
    }
};

@Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mConnReceiver);
    }

    @Override
    protected void onStart() {
        super.onStart();
        this.registerReceiver(this.mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

When I open that Activity the onReceive() is method called everytime.
How to avoid calling it the first time (when opening that Activity)?

1 个答案:

答案 0 :(得分:0)

首次注册时会发送广播(参见粘性广播),解决方案是在isInitialStickyBroadcast的{​​{1}}回调中使用onReceive来了解您是否实际上进行粘性广播并采取相应行动(BroadcastReceiver : isInitialStickyBroadcast