我得到了一个AsyncTask,应该检查对主机名的网络访问。但是doInBackground()永远不会超时。有人知道吗?
public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {
private Main main;
public HostAvailabilityTask(Main main) {
this.main = main;
}
protected Boolean doInBackground(String... params) {
Main.Log("doInBackground() isHostAvailable():"+params[0]);
try {
return InetAddress.getByName(params[0]).isReachable(30);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean... result) {
Main.Log("onPostExecute()");
if(result[0] == false) {
main.setContentView(R.layout.splash);
return;
}
main.continueAfterHostCheck();
}
}
这里是检查互联网连接的最佳方法。这个方法所做的是执行一系列检查“手机是否处于飞行模式,手机是否连接到网络,等等”。如果所有检查都返回true,该方法将从互联网下载一个文件,并查看内容是否与预期值匹配。
与其他通过ping服务器来检查互联网连接的方法相比,这种方法的好处是:
Android运行时在不同的手机上是不同的-所以你可能并不总是能够执行这些命令,如下所示:为什么ping在一些设备上工作,而不是其他设备?
ping服务器并不总是有效,因为登录页面/重定向在wifi网络上,这可能会给人一种连接的错误印象。
这个答案是用Kotlin写的,并使用Fuel库从互联网上下载一个文件,使用methodfetchUrlAsString,但是任何库都可以被替换,只要你确保你的HTTP请求没有被缓存。可以将showConnectionWarning()和hideConnectionWarning()分别等价于互联网连接状态= false和互联网连接状态= true。
private val networkReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val activeNetworkInfo = (context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
if (activeNetworkInfo != null) {
if (activeNetworkInfo.isConnectedOrConnecting) {
//Launches a coroutine to fetch file asynchronously
launch {
try {
//Downloads file from url on the internet - use any library you want here.
val connectionStatus = fetchUrlAsString(<url_for_file_on_internet>)
//check if the contents of the file is as expected
if (connectionStatus == "Connected To Database") {
hideConnectionWarning()
} else {
showConnectionWarning()
}
} catch (e: Exception) {
//Catches an exception - fetchUrlAsString only throws an exception if there is no internet
showConnectionWarning()
}
}
} else {
showConnectionWarning()
}
} else {
showConnectionWarning()
}
}
}
private suspend fun fetchUrlAsString(url: String): String = suspendCoroutine { cont ->
url.httpGet().header(Pair("pragma", "no-cache"), Pair("cache-control", "no-cache")).responseString { _, _, result ->
when (result) {
is Result.Failure -> {
cont.resumeWithException(result.getException())
}
is Result.Success -> {
cont.resume(result.value)
}
}
}
}
您将需要以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
下面是我使用的方法:
public boolean isNetworkAvailable(final Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
更好的是,检查确保它是“连接”的:
public boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
下面是如何使用该方法:
if (isNetworkAvailable(context)) {
// code here
} else {
// code
}
需要许可:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
https://stackoverflow.com/a/16124915/950427
只需创建下面的类来检查internet连接:
public class ConnectionStatus {
private Context _context;
public ConnectionStatus(Context context) {
this._context = context;
}
public boolean isConnectionAvailable() {
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;
}
}
该类仅包含一个返回连接状态布尔值的方法。因此,简单来说,如果该方法找到一个到Internet的有效连接,则返回值为true,否则为false,如果没有找到有效连接。
MainActivity中的下面的方法调用前面描述的方法的结果,并提示用户进行相应的操作:
public void addListenerOnWifiButton() {
Button btnWifi = (Button)findViewById(R.id.btnWifi);
iia = new ConnectionStatus(getApplicationContext());
isConnected = iia.isConnectionAvailable();
if (!isConnected) {
btnWifi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
Toast.makeText(getBaseContext(), "Please connect to a hotspot",
Toast.LENGTH_SHORT).show();
}
});
}
else {
btnWifi.setVisibility(4);
warning.setText("This app may use your mobile data to update events and get their details.");
}
}
在上面的代码中,如果结果为假,(因此没有互联网连接,用户将被带到Android wi-fi面板,在那里他将被提示连接到wi-fi热点。
if(isConnected()){
Toast.makeText(getApplication(),"Thank you",Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder builder =
new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle("Amar Bhat");
builder.setMessage("Oops...You are not connected to Internet!!!");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();
//Toast.makeText(getApplication(),"You are not connected",Toast.LENGTH_SHORT).show();
}
//And outside the class define isConnected()
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
// In minifest add these permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />