简体   繁体   English

使用类扩展asynctask来检查android活动中的互联网连接

[英]Using class extending asynctask to check internet connection in android activity

By checking some questions on here I have managed to create the below class in order to check whether the user has an active internet connection. 通过检查这里的一些问题,我设法创建了以下类,以检查用户是否具有有效的互联网连接。 I want to use this in my android activities to check the connection before I load any data from the internet. 我想在我的android活动中使用它来检查连接,然后再从互联网加载任何数据。 I would like to ask if this is a suitable way of checking the user's internet connection and I would like someone to provide an example of how this would be called from within an activity (how to pass the context to it and how to obtain the true/false response back in my android activity. 我想问一下这是否是检查用户互联网连接的合适方法,并且我希望有人提供一个示例,说明如何从活动中调用该活动(如何将上下文传递给活动以及如何获得true/false响应返回到我的android活动中。

public class ConnectionStatus  {
private Context context;

public ConnectionStatus(Context context){
    this.context=context;
}
public static boolean isNetworkAvailable(Context c) {
    NetworkInfo netInfo = null;
    try {
        ConnectivityManager cm = (ConnectivityManager) c
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        netInfo = cm.getActiveNetworkInfo();
    } catch (SecurityException e) {
        e.printStackTrace();
    }
    return netInfo != null && netInfo.isConnectedOrConnecting();
}
public boolean CheckConnection() {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 204 &&
                    urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.e("TAG", "Error checking internet connection", e);
        }
    } else {
        Log.d("TAG", "No network available!");
    }
    return false;
}
}

I would get the network info outside the Async Task since it would be easier for you to handle how to react on the given network status. 我会在“异步任务”之外获取网络信息,因为您可以更轻松地处理如何对给定的网络状态做出反应。

For the Async Task, you could make it an inner class of your Activity, and check for the network status before calling the execute method of the Async Task. 对于异步任务,您可以使其成为Activity的内部类,并在调用异步任务的execute方法之前检查网络状态。

public class MyActivity extends Activity{

...
...
  private static boolean isNetworkAvailable(Context c) {
    NetworkInfo netInfo = null;
    try {
      ConnectivityManager cm = (ConnectivityManager) c
            .getSystemService(Context.CONNECTIVITY_SERVICE);
      netInfo = cm.getActiveNetworkInfo();
    } catch (SecurityException e) {
      e.printStackTrace();
    // Something bad happen, better return false.
      return false;
    }
    return netInfo != null && netInfo.isConnectedOrConnecting();
  }

//Let's assume you will call your data from the internet like this
  private void getDataFromTheInternet(){
  if (isNetworkAvailable){
     ConnectionStatus cStatus = new ConnectionStatus(getApplicationContext());
    cStatus.execute();
  }else{
  //Prevent the user that there is not a network connection
  }
}

Now, remove the isNetworkAvailable methof from the Asynk Task and there you go. 现在,从Asynk任务中删除isNetworkAvailable methof,然后开始。

Additionally you could use a BroadCast receiver to check everytime the connection status changes so your application can react when it's offline or online following this tutorial 此外,您可以使用BroadCast接收器在每次连接状态更改时进行检查,以便您的应用程序可以在脱机或在线时做出反应,请按照本教程进行操作

Here is an example of an Activity class that includes an AsyncTask, and shows how you could use your ConnectionStatus class in the updated version of your question. 这是一个包含AsyncTask的Activity类的示例,并显示了如何在问题的更新版本中使用ConnectionStatus类。

public class MainActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.text);

        //Create Strings to pass to varargs of AsyncTask
        String s1 = "test1";
        String s2 = "test2";
        new MyAsync().execute(s1, s2);

    }

    class MyAsync extends AsyncTask<String, String, String> {

        ConnectionStatus status;

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(String... params) {

            String retVal = null;

            //Instantiate your object, use MainActivity.this for Context
            status = new ConnectionStatus(MainActivity.this);

            //capture varargs
            String sOne = params[0];
            String sTwo = params[1];

            boolean something = false;

            //Check network connectivity:
            if (status.CheckConnection()){

                //You have internet, do your network operations here
                //...............

                //Just here for an example:
                if (something == true){
                    retVal = sOne;
                }
                else{
                    retVal = sTwo;
                }

            }

            return retVal;
        }

        @Override
        protected void onPostExecute(String arg) {
            //Update UI here, this runs on the Main UI thread of the Activity
            if (arg != null){
                textView.setText(arg);
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM