0

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%3AAndroid%2Fdata%2Fnet.wargaming.wot.blitz%2Ffiles%2Fpacks/document/primary%3AAndroid%2Fdata%2Fnet.wargaming.wot.blitz%2Ffiles%2Fpacks")) {
    my_couter += 1;
}
if (_checkPermission("content://com.android.externalstorage.documents/tree/primary%3AMTG%20MODS/document/primary%3AMTG%20MODS")) {
    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) {

}
});

2 Answers 2

3

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();
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.