gpt4 book ai didi

android - 如何检查android中是否启用了互联网访问?

转载 作者:太空狗 更新时间:2023-10-29 15:31:20 26 4
gpt4 key购买 nike

我正在尝试创建一个连接到网络服务器并检索数据的应用程序,我想做一些功能

  1. 当我点击我的应用程序时,它首先检查是否启用了互联网访问?如果它被启用它启动应用程序,否则打开互联网访问设置..之后它重定向到我的应用程序....
  2. 当应用程序连接到网络服务器时,如果连接不成功,连接将在特定时间后超时。

最佳答案

在我的一个应用程序中,我有一个这样定义的类:

    public class ConnectionDetector {

private Context _context;

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

/**
* Checking for all possible internet providers
* **/
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;
}
}

在我需要检查连接状态的 Activity 中,我使用这个:

    // DEFINE THIS AS A GLOBAL VARIABLE
AlertDialogManager alert = new AlertDialogManager();

onCreate() 中:

    ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}

哦。差点忘了。如果您还需要将用户重定向到设置面板以激活 Internet,您可以使用这样的 Intent:

您可以在 AlertDialog 中提示用户并让他们选择是否愿意。如果是,运行这段代码。

Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(intent);

编辑:

我错过了明显的(Commonsware 在他的评论中指出了这一点)。

您需要将 ACCESS_NETWORK_STATE 权限添加到您的 list 文件。

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

关于android - 如何检查android中是否启用了互联网访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14922098/

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