gpt4 book ai didi

android - 在显示 Activity 之前,如何在android中使用来自广播接收器的数据

转载 作者:行者123 更新时间:2023-11-29 21:20:38 25 4
gpt4 key购买 nike

我正在使用接收器以了解手机是否已连接到互联网。

我正在使用这段代码:

public class SearchFragment extends Fragment {

private Boolean netOk = false;

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);

ConnectionChangeReceiver1 netReceiver = new ConnectionChangeReceiver1();
IntentFilter filterNet = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
getActivity().registerReceiver(netReceiver, filterNet);
}

@Override
public void onResume() {
super.onResume();

if(netOk){
Toast.makeText(getActivity(),"U GOT NET" , Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(),"U DON'T GOT NET" , Toast.LENGTH_LONG).show();
}
}


public class ConnectionChangeReceiver1 extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

boolean isConnected = activeNetInfo != null
&& activeNetInfo.isConnectedOrConnecting();

if (isConnected){
netOk= true;
}else{
netOk= false;
}
}
}
}

问题是,netOk 保持错误。现在我明白了,只有在 onCreateonStartonResume 之后,才会调用接收器类。

所以问题是:如果我想在向用户显示 Activity 之前知道是否有互联网连接,我应该怎么做?

最佳答案

您可以试试这个以同步获取响应。

public static boolean checkInternetConnection(Context context) {

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm != null && cm.getActiveNetworkInfo().isConnected()
&& cm.getActiveNetworkInfo().isAvailable()) {
return true;
}
return false;
}

关于android - 在显示 Activity 之前,如何在android中使用来自广播接收器的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20782965/

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