Call AsyncTask inside a thread

I am working in an Android application and I want to call AsyncTask from the main UI thread. For this, I want to call my AsyncTask from the stream.

This is the method that I call from my main UI thread. It works correctly

CommonAysnk mobjCommonAysnk = new CommonAysnk(this, 1); mobjCommonAysnk.execute(); 

CommonAysnk is my AsyncTask class. I want to pass my activity and integer parameter to the AsyncTask constructor. How can I call this from a stream as shown below.

  Thread t = new Thread() { public void run() { try { CommonAysnk mobjCommonAysnk = new CommonAysnk(this, 1); mobjCommonAysnk.execute(); } catch (Exception ex) { }}}; t.start(); 

When I tried to call it from the stream, and I can not pass the activity parameter correctly.

This is the CommonAysnk class. Please study it

 public class CommonAysnk extends AsyncTask<URL, Integer, String> { private Common mobjCommon = null; private Activity mobjActivity = null; private int mcallIntentcond = 0; private ProgressDialog mProcessDialog = null; public CommonAysnk(Activity activity, int condition) { mobjActivity = activity; mcallIntentcond = condition; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); mProcessDialog.dismiss(); } @Override protected void onPreExecute() { super.onPreExecute(); mobjCommon = new Common(); mProcessDialog = mobjCommon.showProgressDialog(mobjActivity, "", "Loading...", false); } @Override protected String doInBackground(URL... params) { try { Thread.sleep(500); } catch (InterruptedException e) { } switch (mcallIntentcond) { case 1: Intent i=new Intent(mobjActivity, Home.class); mobjActivity.startActivity(i); mobjActivity.finish(); break; } return null; } } 

How can we do this. Thanks

+4
source share
4 answers

There is no reason to run AsyncTask in a thread like this, you can call it in a user interface thread. AsyncTask controls the threads for you.

The code entered in the doInBackground method runs automatically in the background thread, the other methods in your AsyncTask run in the user interface thread, and you can safely interact with the user interface.

+3
source

You cannot use this directly from the stream, as the context changes from your MainActivity to the stream class. So you need to do the following:

 CommonAysnk mobjCommonAysnk = new CommonAysnk(ActivityName.this, 1); 

And you can run AsyncTask from a thread, no hard and fast rules regarding this.

+2
source

using

  CommonAysnk mobjCommonAysnk = new CommonAysnk(ClassName.this, 1); mobjCommonAysnk.execute(); 
+1
source

It is obligatory to call asynctask only from the main thread, otherwise it may fall at runtime when we try to touch the interface from the onPreExecute or onProgressUpdate or onPostExecute .

+1
source

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


All Articles