简体   繁体   English

如何在JAVA(Android Studio)中使用AsynsTask

[英]How to use AsynsTask in JAVA (Android Studio)

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我需要它在按下按钮时在后台执行此操作并将结果(my_couter)返回给我

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

}
});

AsyncTask is deprecated now. AsyncTask 现已弃用。 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();

You can simply create an inner class and extend it from AsyncTask<String, String, String> .您可以简单地创建一个内部类并从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.现在,根据您的要求,您将不会使用 onPreExecute。

But, you should use doInBackground - this is were you will update your variable namely my_counter但是,您应该使用doInBackground - 这是您将更新变量即my_counter

Lastly, when the AsyncTask is completed, the onPostExecute is called and there you will return your variable respectively.最后,当 AsyncTask 完成时,将调用onPostExecute并在那里分别返回变量。

Do give it a try.试试看吧。

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

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