gpt4 book ai didi

java - android中如何显示未连接互联网

转载 作者:行者123 更新时间:2023-12-01 18:33:20 26 4
gpt4 key购买 nike

我需要帮助。我想要一个 toast 来显示我的应用程序中的互联网状态。它适用于 wifi 和移动数据包(移动互联网)。但当互联网完全断开时,它什么也没有显示。我不知道该怎么做。这是我的代码

public class ConnectivityReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Log.d("myapp", "action: " + intent.getAction());
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();

if(isConnected)
{
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
{
Toast toast = Toast.makeText(context, "Connected to wifi", Toast.LENGTH_LONG);
toast.show();
}
else if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
{
Toast toast = Toast.makeText(context, "Connected to Mobile Data Pakage", Toast.LENGTH_LONG);
toast.show();

}
else
{
Toast toast = Toast.makeText(context, "Not Connected", Toast.LENGTH_LONG);
toast.show();

}

也尝试一下,但编译器显示错误。请帮助我。提前致谢。

 else if(activeNetwork.getType() == ConnectivityManager.EXTRA_NO_CONNECTIVITY)
{
Toast toast = Toast.makeText(context, "Not Connected", Toast.LENGTH_LONG);
toast.show();

声明

 <receiver android:name="com.networkstatechange.ConnectivityReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

最佳答案

公共(public)类ConnectionDetector{

private Context _context;

public ConnectionDetector(Context context){
this._context = context;
}

public boolean isConnectingToInternet(){
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)
{
return true;
}

}
return false;
}

}

创建这个类

并在您的接收器 onreceive 中使用 isConnecting to internet 方法应该可以正常工作

也许编码:)

关于java - android中如何显示未连接互联网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23156396/

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