gpt4 book ai didi

android - 如何使用 CONNECTIVITY_CHANGE 定义 Broadcastreceiver?

转载 作者:行者123 更新时间:2023-11-29 19:07:11 26 4
gpt4 key购买 nike

我是 android 初学者,想声明一个对 CONNECTIVITY_CHANGE 使用react的广播接收器。我尝试了以下方法:

private void checkInternet () {
IntentFilter ifilter = new IntentFilter ("android.net.conn.CONNECTIVITY_CHANGE");
broadcastreceiver = new BroadcastReceiver () {
@Override
public void onReceive (Context Context, Intent Intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService (getApplicationContext (). CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo ();
if (networkInfo! = null && networkInfo.getState () == NetworkInfo.State.CONNECTED)
Toast.makeText (getApplicationContext (), "Internet", Toast.LENGTH_SHORT) .show ();
else
Toast.makeText (getApplicationContext (), "No Internet", Toast.LENGTH_SHORT) .show ();
}
};
this.registerReceiver (broadcastreceiver, ifilter);
}

在 Actitvity.onCreate 中,我调用 checkInternet。当我断开 Internet 连接时,会显示“No Internet”和“Internet”这两个消息。当我连接到 Internet 时,“No Internet”和“Internet”这两个消息以相同的顺序再次出现。有人可以告诉我为什么 Broadcastreceiver 启动 2 次并显示 2 个不同的状态 pro Start 吗?提前谢谢你

最佳答案

如果您只需要检查互联网连接,您可以使用以下方法。在你的 Activity 中

 @Override
protected void onCreate(Bundle savedInstanceState){
ConnectionStateMonitor connectionStateMonitor = new ConnectionStateMonitor();
connectionStateMonitor.enable(this);
}

并在你的 Activity 中添加这个类

public class ConnectionStateMonitor extends ConnectivityManager.NetworkCallback {

final NetworkRequest networkRequest;

public ConnectionStateMonitor() {
networkRequest = new NetworkRequest.Builder().
addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();
}

public void enable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.registerNetworkCallback(networkRequest , this);
}
// Likewise, you can have a disable method that simply calls ConnectivityManager#unregisterCallback(networkRequest) too.

@Override
public void onAvailable(Network network) {
//do what you want when Connection is available
}
@Override
public void onLost(Network network){
//Connection Lost
}
}

我认为这比使用广播接收器更容易

关于android - 如何使用 CONNECTIVITY_CHANGE 定义 Broadcastreceiver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46766790/

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