gpt4 book ai didi

java - 无法设置互联网连接的广播接收器,如下是我的代码

转载 作者:太空宇宙 更新时间:2023-11-04 11:01:06 27 4
gpt4 key购买 nike

我已经在util包中完成了这个方法类,但问题是如何调用这个方法来检查互联网连接,请帮忙。因为我的代码运行良好,没有错误

public class NetworkChangeReceiver extends BroadcastReceiver {

private static final String LOG_TAG = "NetworkChangeReceiver";
private boolean isConnected = false;

@Override
public void onReceive(Context context, Intent intent) {
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
}

private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if (!isConnected) {
Log.v(LOG_TAG, "Now you are connected to Internet!");
Toast.makeText(context, "Internet availablle via Broadcast receiver", Toast.LENGTH_SHORT).show();
isConnected = true;
// do your processing here ---
// if you need to post any data to the server or get
// status
// update from the server
}
return true;
}
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
Toast.makeText(context, "Internet NOT availablle via Broadcast receiver", Toast.LENGTH_SHORT).show();
isConnected = false;
return false;
}
}

最佳答案

Using broadcast receiver, your app will be automatically notified when there is a change in network connection.

   boolean isConnected = NetworkChangeReceiver.isNetworkAvailable(YourACTIVITY.this);
System.out.println("STATUS"+isConnected );

关于java - 无法设置互联网连接的广播接收器,如下是我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46883454/

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