Home > database >  How to use AsynsTask in JAVA (Android Studio)
How to use AsynsTask in JAVA (Android Studio)

Time:12-20

I have the following code:

int my_couter = 0;

if (SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager()) {
        my_couter  = 1;
}
if (ContextCompat.checkSelfPermission(MainActivity.this, READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    my_couter  = 1;
}
if (_checkPermission("content://com.android.externalstorage.documents/tree/primary:Android/data/net.wargaming.wot.blitz/files/packs/document/primary:Android/data/net.wargaming.wot.blitz/files/packs")) {
    my_couter  = 1;
}
if (_checkPermission("content://com.android.externalstorage.documents/tree/primary:MTG MODS/document/primary:MTG MODS")) {
    my_couter  = 1;
}

I need it to execute this in the background when a button is pressed and return the result (my_couter) to me

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View _view) {

}
});

CodePudding user response:

AsyncTask is deprecated now. Better you can use this.

  new Thread(new Runnable() {
            @Override
            public void run() {

           //perform background task here and finally update the UI with result this way -

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                      //Do something on UiThread

                    }
                });

            }
        }).start();

CodePudding user response:

You can simply create an inner class and extend it from AsyncTask<String, String, String>. This allows you to override three main callbacks.

  • protected void onPreExecute()
  • protected String doInBackground(String... params)
  • protected void onPostExecute(String s)

Now, as per your requirement, you wont be using the onPreExecute.

But, you should use doInBackground - this is were you will update your variable namely my_counter

Lastly, when the AsyncTask is completed, the onPostExecute is called and there you will return your variable respectively.

Do give it a try.

  • Related