gpt4 book ai didi

android - android中的网络连接检查

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:13:24 27 4
gpt4 key购买 nike

我正在尝试检查网络是否可用。
但在我的模拟器中它总是显示connected(在断开互联网连接之后)

我的代码有没有错误。我正在连接wifi

代码:

public class AndroidConnectivityActivity extends Activity
{
Button checkBtn;

/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBtn = (Button) findViewById(R.id.button1);

checkBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(isInternetOn())
{
Toast.makeText(getBaseContext(), "Connected",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Not connected",
Toast.LENGTH_SHORT).show();
}
}});
}

public final boolean isInternetOn()
{
ConnectivityManager connec = (ConnectivityManager) getSystemService
(Context.CONNECTIVITY_SERVICE);

if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)
||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING)
||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING)
||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED))
{
return true;
}

else if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED)
|| (connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED))
{
return false;
}

return false;
}
}

最佳答案

使用下面的代码

public static boolean isInternetAvailable(Context context)
{
boolean isInternetAvailable = false;

try
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

if(networkInfo != null && (networkInfo.isConnected()))
{
isInternetAvailable = true;
}
}
catch(Exception exception)
{
// Do Nothing
}

return isInternetAvailable;
}

也可以在真机上试试

在 Activity 中使用 onCreate 方法中的代码,如

if(isInternetAvailable(this))
{
Toast toast = Toast.makeText(this, "internet available", Toast.LENGTH_SHORT);
toast.show();
}
else
{
Toast toast = Toast.makeText(this, "internet not available", Toast.LENGTH_SHORT);
toast.show();
}

所需的 list 权限

<uses-permission
android:name="android.permission.INTERNET" />

<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />

关于android - android中的网络连接检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047344/

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