我得到了一个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();
}
}
更新29/06/2015
如果你正在使用Xamarin。Android和想要检查连接,你可以使用Nuget包,这将给你在多个平台上的功能。好的候选人在这里和这里。
[更新结束]
The Answers above are quite good, but they are all in Java, and almost all of them check for a connectivity. In my case, I needed to have connectivity with a specific type of connection and I am developing on Xamarin.Android. Moreover, I do not pass a reference to my activities Context in the Hardware layer, I use the Application Context. So here is my solution, in case somebody comes here with similar requirements. I have not done full testing though, will update the answer once I am done with my testing
using Android.App;
using Android.Content;
using Android.Net;
namespace Leopard.Mobile.Hal.Android
{
public class AndroidNetworkHelper
{
public static AndroidNetworkStatus GetWifiConnectivityStatus()
{
return GetConnectivityStatus(ConnectivityType.Wifi);
}
public static AndroidNetworkStatus GetMobileConnectivityStatus()
{
return GetConnectivityStatus(ConnectivityType.Mobile);
}
#region Implementation
private static AndroidNetworkStatus GetConnectivityStatus(ConnectivityType connectivityType)
{
var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
var wifiNetworkInfo = connectivityManager.GetNetworkInfo(connectivityType);
var result = GetNetworkStatus(wifiNetworkInfo);
return result;
}
private static AndroidNetworkStatus GetNetworkStatus(NetworkInfo wifiNetworkInfo)
{
var result = AndroidNetworkStatus.Unknown;
if (wifiNetworkInfo != null)
{
if (wifiNetworkInfo.IsAvailable && wifiNetworkInfo.IsConnected)
{
result = AndroidNetworkStatus.Connected;
}
else
{
result = AndroidNetworkStatus.Disconnected;
}
}
return result;
}
#endregion
}
public enum AndroidNetworkStatus
{
Connected,
Disconnected,
Unknown
}
下面是我用于可达性检查的Kotlin版本,
芬兰湾的科特林MyReachability
object MyReachability {
private val REACHABILITY_SERVER = "http://google.com" // can be any URL you want
private fun hasNetworkAvailable(context: Context): Boolean {
val service = Context.CONNECTIVITY_SERVICE
val manager = context.getSystemService(service) as ConnectivityManager?
val network = manager?.activeNetworkInfo
Log.d(classTag, "hasNetworkAvailable: ${(network != null)}")
return (network != null)
}
fun hasInternetConnected(context: Context): Boolean {
if (hasNetworkAvailable(context)) {
try {
val connection = URL(REACHABILITY_SERVER).openConnection() as HttpURLConnection
connection.setRequestProperty("User-Agent", "Test")
connection.setRequestProperty("Connection", "close")
connection.connectTimeout = 1500
connection.connect()
Log.d(classTag, "hasInternetConnected: ${(connection.responseCode == 200)}")
return (connection.responseCode == 200)
} catch (e: IOException) {
Log.e(classTag, "Error checking internet connection", e)
}
} else {
Log.w(classTag, "No network available!")
}
Log.d(classTag, "hasInternetConnected: false")
return false
}
}
您甚至可以根据策略和限制将REACHABILITY_SERVER作为参数传递,例如,当您在中国时,您可以检查https://baidu.com而不是https://google.com。
调用示例中,
val webLoaderThread = Thread {
if (MyReachability.hasInternetConnected(this)){
runOnUiThread {
//mWebView.loadUrl(LANDING_SERVER) // connected
}
} else {
runOnUiThread {
//showDialogNoNetwork() // not connected
}
}
}
webLoaderThread.start()
安卓系统权限
不要忘记将以下权限添加到你的AndroidManifest.xml中
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
这里是检查互联网连接的最佳方法。这个方法所做的是执行一系列检查“手机是否处于飞行模式,手机是否连接到网络,等等”。如果所有检查都返回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" />
Jetpack组成/芬兰湾的科特林
根据Levite的回答,我们可以在Jetpack Compose中使用这个组合:
val DNS_SERVERS = listOf("8.8.8.8", "1.1.1.1", "4.2.2.4")
const val INTERNET_CHECK_DELAY = 3000L
@Composable
fun InternetAwareComposable(
dnsServers: List<String> = DNS_SERVERS,
delay: Long = INTERNET_CHECK_DELAY,
successContent: (@Composable () -> Unit)? = null,
errorContent: (@Composable () -> Unit)? = null,
onlineChanged: ((Boolean) -> Unit)? = null
) {
suspend fun dnsAccessible(
dnsServer: String
) = try {
withContext(Dispatchers.IO) {
Runtime.getRuntime().exec("/system/bin/ping -c 1 $dnsServer").waitFor()
} == 0
} catch (e: Exception) {
false
}
var isOnline by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
while (true) {
isOnline = dnsServers.any { dnsAccessible(it) }
onlineChanged?.invoke(isOnline)
delay(delay)
}
}
if (isOnline) successContent?.invoke()
else errorContent?.invoke()
}