gpt4 book ai didi

android - OnReceive() 方法自动触发

转载 作者:行者123 更新时间:2023-11-30 01:31:09 28 4
gpt4 key购买 nike

我在 Activity 中创建了一个接收器,用于在连接互联网时自动调用网络服务。

代码如下

//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));
}

当我打开那个 Activity 时,onReceive() 方法每次都会被调用。
如何避免第一次调用它(在打开该 Activity 时)?

最佳答案

当你第一次注册时发送广播(cf sticky broadcast),一个解决方案是在你的BroadcastReceiver的onReceive回调中使用isInitialStickyBroadcast 了解您是否真的在进行粘性广播并采取相应行动 ( BroadcastReceiver : isInitialStickyBroadcast )

关于android - OnReceive() 方法自动触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745215/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com