[英]how to stop asynctask when internet is connected but no internet access in android
String url = "http://xyzcloud.com/xyz/xyz.php";
this the url am trying to get the data from cloud,if internet is connected then async task will execute i wrote this method for checking wether internet is connected or not, here in my mobile wifi is connetecd when am trying to execute it is giving exception 这个URL试图从云中获取数据,如果连接了互联网,那么异步任务将执行。我编写了此方法来检查是否连接了互联网,这在我试图执行时在我的移动wifi中是connetecd,它给出了异常
public boolean checkOnlineState()
{
boolean val = false;
ConnectivityManager CManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NInfo = CManager.getActiveNetworkInfo();
if (NInfo != null && NInfo.isConnectedOrConnecting()) {
try {
if (InetAddress.getByName(url).isReachable(10000))
{
// host reachable
val=true;
Log.e("checkOnlineState", "" + val);
}
else
{
// host not reachable
val = false;
Log.e("checkOnlineState", "" + val);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return val;
}
import android.app.Service;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context) {
this.context = context;
}
public boolean isConnected() {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Service.CONNECTIVITY_SERVICE);
if ( connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
}
Then for example, you can make use of it: 然后,例如,您可以使用它:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConnectionDetector cd = new ConnectionDetector(this);
if (cd.isConnected()) {
// do something
} else {
//do something
}
setContentView(R.layout.activity_main);
}
}
I use this approach in my apps (which requires Internet connection) and didn't face any problem yet. 我在我的应用程序(需要Internet连接)中使用了这种方法,但是还没有遇到任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.