How to stop Asyn task in onPreExecute?

I check the status of the Internet connection in onPreExecute (), and if there is no Internet connection, it should not do doInBackground () and onPostExecute ()

new getStatus().execute(); private class getStatus extends AsyncTask<Void, Void, Void> { 
+5
source share
3 answers

You set the flag in AsyncTask to onPreExecute. Check this flag in two other functions and return immediately if the flag is true.

+4
source

Do it:

 public boolean hasInternetConnection(final Context context) { final ConnectivityManager connectivityManager = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); boolean isConnected = networkInfo.isConnectedOrConnecting() && networkInfo.isAvailable() && networkInfo.isConnected(); return isConnected; } 

put this in onCreate () or anywhere you want to complete the task, and depending on the result:

 if(hasInternetConnection(YourActivity.this){ //executeTask }else{ //redirect user to Wifi Settings with dialog } 

Hope this helps !!!

+1
source

Since the Internet connection may disappear at any time, why not just complete the task and handle the IOException, how does this happen? If there is no connectivity, I think creating an HTTP request or whatever you do, it worked immediately. Of course, you could add a check before you try, but such a check should not replace error handling during a network request.

I would probably put all the logic in doInBackground. If I first add a connection check, I would handle it the same way as any network exceptions that occur during the actual request. As for the actual handling of errors, you can save the error code as a member in your async, you could work in asynctask on a custom class containing both data and an error code, or you could even have doInBackground return null in case of an error and handle errors directly from doInBackground.

+1
source

Source: https://habr.com/ru/post/1244997/


All Articles