Android 如何执行检查internet连接的异步任务

Android 如何执行检查internet连接的异步任务,android,android-asynctask,Android,Android Asynctask,我有以下代码,我试图通过编程检查是否存在internet连接。 因为我得到了一个NetworkOnMainThreadException,建议我使用AsyncTask。 我想对hasActiveInternetConnection(上下文)执行网络操作,如果连接到网络,则返回true,否则返回false。 如何使用AsyncTask执行此操作? public class NetworkUtil extends AsyncTask<String, Void, String>{

我有以下代码,我试图通过编程检查是否存在internet连接。
因为我得到了一个NetworkOnMainThreadException,建议我使用AsyncTask。
我想对hasActiveInternetConnection(上下文)执行网络操作,如果连接到网络,则返回true,否则返回false。
如何使用AsyncTask执行此操作?

 public class NetworkUtil extends AsyncTask<String, Void, String>{
        Context context;

        public NetworkUtil(Context context){
            this.context = context;
         }

    private ProgressDialog dialog;

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... arg0) {
        if (new CheckNetwork(context).isNetworkAvailable()) 
        {
             try {
                 HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                 urlc.setRequestProperty("User-Agent", "Test");
                 urlc.setRequestProperty("Connection", "close");
                 urlc.setConnectTimeout(1500); 
                 urlc.connect();
                 boolean url= (urlc.getResponseCode() == 200);
                 String str = String.valueOf(url);
                 return str;
             } catch (IOException e) {

             }
         } 


            // your get/post related code..like HttpPost = new HttpPost(url);
         else {
            Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show();
        }


        return null;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
    }
公共类NetworkUtil扩展异步任务{
语境;
公共NetworkUtil(上下文){
this.context=上下文;
}
私人对话;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的字符串doInBackground(字符串…arg0){
if(新建CheckNetwork(上下文).isNetworkAvailable())
{
试一试{
HttpURLConnection urlc=(HttpURLConnection)(新URL(“http://www.google.com);
setRequestProperty(“用户代理”、“测试”);
setRequestProperty(“连接”、“关闭”);
设置连接超时(1500);
connect();
布尔url=(urlc.getResponseCode()==200);
String str=String.valueOf(url);
返回str;
}捕获(IOE异常){
}
} 
//与get/post相关的代码..比如HttpPost=newhttppost(url);
否则{
Toast.makeText(上下文,“没有互联网!”,Toast.LENGTH_SHORT.show();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
if(dialog.isShowing()){
dialog.dismise();
}
}
}

您的
异步任务应如下所示:

 private class NetworkUtilTask extends AsyncTask<Void, Void, Boolean>{
    Context context;

    public NetworkUtilTask(Context context){
        this.context = context;
     }

     protected Boolean doInBackground(Void... params) {
         return hasActiveInternetConnection(this.context);
     }
     protected void onPostExecute(Boolean hasActiveConnection) {
         Log.d(LOG_TAG,"Success=" + hasActiveConnection);
     }
 }

使用此类检查internet连接

public class CheckNetwork {
private Context context;

public CheckNetwork(Context context) {
    this.context = context;
}

public boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}

然后

将此ASynTask用于httppost

public class NetworkUtil extends AsyncTask<String, Void, String> {

private ProgressDialog dialog;

@Override
protected void onPreExecute() {
    dialog = new ProgressDialog(YourActivity.this);
    dialog.setMessage("Loading...");
    dialog.setCancelable(false);
    dialog.show();
    super.onPreExecute();
}

@Override
protected String doInBackground(String... arg0) {
    if (new CheckNetwork(YourActivity.this).isNetworkAvailable()) {
        // your get/post related code..like HttpPost = new HttpPost(url);
    } else {
        // No Internet 
        // Toast.makeText(YourActivity.this, "no internet!", Toast.LENGTH_SHORT).show();
    }
    return null;
}
@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    if (dialog.isShowing()) {
        dialog.dismiss();
    }
}
公共类NetworkUtil扩展异步任务{
私人对话;
@凌驾
受保护的void onPreExecute(){
dialog=新建进度dialog(YourActivity.this);
setMessage(“加载…”);
对话框。可设置可取消(false);
dialog.show();
super.onPreExecute();
}
@凌驾
受保护的字符串doInBackground(字符串…arg0){
if(新建CheckNetwork(YourActivity.this).isNetworkAvailable()){
//与get/post相关的代码..比如HttpPost=newhttppost(url);
}否则{
//没有互联网
//Toast.makeText(YourActivity.this,“没有互联网!”,Toast.LENGTH_SHORT.show();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
if(dialog.isShowing()){
dialog.dismise();
}
}
但是我发现了一个非常好的答案:你向google.com发送一个请求!!:)如果你愿意,你也可以尝试通过unix命令ping到google

这家伙正在使用一个线程,等待一点答案,然后返回一个布尔值。你在处理程序中处理你的工作人员。这是他的代码:

public static void isNetworkAvailable(final Handler handler, final int timeout) {
    // ask fo message '0' (not connected) or '1' (connected) on 'handler'
    // the answer must be send before before within the 'timeout' (in milliseconds)

    new Thread() {
        private boolean responded = false;   
        @Override
        public void run() { 
            // set 'responded' to TRUE if is able to connect with google mobile (responds fast) 
            new Thread() {      
                @Override
                public void run() {
                    HttpGet requestForTest = new HttpGet("http://m.google.com");
                    try {
                        new DefaultHttpClient().execute(requestForTest); // can last...
                        responded = true;
                    } 
                    catch (Exception e) {
                    }
                } 
            }.start();

            try {
                int waited = 0;
                while(!responded && (waited < timeout)) {
                    sleep(100);
                    if(!responded ) { 
                        waited += 100;
                    }
                }
            } 
            catch(InterruptedException e) {} // do nothing 
            finally { 
                if (!responded) { handler.sendEmptyMessage(0); } 
                else { handler.sendEmptyMessage(1); }
            }
        }
    }.start();
}
…并启动测试:

isNetworkAvailable(h,2000); // get the answser within 2000 ms

你想检查你是否有连接做员工?或者你想等到你有互联网连接做员工?@ahmed我只想检查互联网连接,如果连接存在,然后我想返回true!看起来不错,应该是正确的答案。我不明白为什么在异步任务中使用此选项?请你解释一下这个技巧的优点或用例?因为上下文被传递给构造函数,所以我使用了
this
,因为还有任务变量
context
。基本上这只是为了避免歧义。我不能将受保护的字符串doInBackground(String…params)更改为受保护的布尔doInBackground(Void…params)我怎么能这么做?泰!我很抱歉弄糊涂了,我用的是正常的词“this”我的问题是,为什么要使用异步任务来检查internet连接?thxagain@ahmed_khan_89我的帖子是试图回答OP的问题,但你是对的。不需要异步只是为了看看你是否有这么多的连接…我已经更新了上面的代码…你能确认我是否继续吗正确的方法。我如何在另一个类中获得返回str;值?正确的方法有两件事…1.调用NetworkUtil类时发送您的活动。这不是getApplicationContext()。2.将str变量作为类变量,但声明..public static String str;并写入…dialog=new ProgressDialog(YourActivity.this);dialog.setMessage(“加载…”);dialog.setCancelable(false);dialog.show();in onPreExecute()methodTy!!很快就会尝试!这应该是可以接受的答案。Google.com可能有一天会停止;-)ty…尝试一下!工作正常!马上确认是否工作正常!对于代码顺便说一句:)工作完美无瑕:)
public static void isNetworkAvailable(final Handler handler, final int timeout) {
    // ask fo message '0' (not connected) or '1' (connected) on 'handler'
    // the answer must be send before before within the 'timeout' (in milliseconds)

    new Thread() {
        private boolean responded = false;   
        @Override
        public void run() { 
            // set 'responded' to TRUE if is able to connect with google mobile (responds fast) 
            new Thread() {      
                @Override
                public void run() {
                    HttpGet requestForTest = new HttpGet("http://m.google.com");
                    try {
                        new DefaultHttpClient().execute(requestForTest); // can last...
                        responded = true;
                    } 
                    catch (Exception e) {
                    }
                } 
            }.start();

            try {
                int waited = 0;
                while(!responded && (waited < timeout)) {
                    sleep(100);
                    if(!responded ) { 
                        waited += 100;
                    }
                }
            } 
            catch(InterruptedException e) {} // do nothing 
            finally { 
                if (!responded) { handler.sendEmptyMessage(0); } 
                else { handler.sendEmptyMessage(1); }
            }
        }
    }.start();
}
Handler h = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        if (msg.what != 1) { // code if not connected

        } else { // code if connected

        }   
    }
};
isNetworkAvailable(h,2000); // get the answser within 2000 ms