AsyncTask 已弃用?使用什么方法代替 onPreExecute 和 onPostExecute?

问题描述 投票:0回答:3

在我的旧项目中,我使用了 AsyncTask,但它已被弃用,那么我使用什么方法来代替这个呢? 如果我们使用线程,则在 AsyncTask 中具有 onbackground、onPreExecute 和 onPostExecute Override 方法,其中本节在线程中调用。有没有什么替代方法。能给我解决办法吗?

Java代码:

      public class getDetailsfromWeb extends AsyncTask<Void, Void, String> {

      @Override
      protected String doInBackground(Void... params) {

        if (paymentSync == null)

            paymentSync = new ReceivePaymentSync(getActivity());

        allCreditCardModel = new AllCreditCardModel();

        allCreditCardModel = paymentSync.getGetCreditCardById(CrediCardId);

        handler.post(allCreditRunnable);

        return null;
    }

    /**
     * @param string
     */
    public void execute(String string) {

        // TODO Auto-generated method stub
    }

    protected void onPreExecute() {

        showProgress();

    }

    @Override
    protected void onPostExecute(String result) {

        progress.dismiss();

    }
}
android android-studio android-asynctask asynctaskloader
3个回答
6
投票

这是一个简单的例子,无论如何我也会看看 WorkManager 库:

Executors.newSingleThreadExecutor().execute(() -> {

    Handler mainHandler = new Handler(Looper.getMainLooper());

      //sync calculations

    mainHandler.post(() -> {
      //Update UI
    });

    //other sync calcs.

    mainHandler.post(() -> {
      //Update UI
    });

  });   

5
投票

只需使用线程即可。

onPreExecute 代码位于构造函数中。

doInBackground 代码进入 run() 中。

onPostExecute 代码进入 runOnUiThread 的可运行对象的运行中,您可以在 run() 结束时调用该可运行对象。


0
投票

试试这个库

任务KT

科特林

Task {//Outer Task
        Task.Foreground.start {
            Toast.makeText(
                this@MainActivity,
                "This is how you can toast with Task",
                Toast.LENGTH_SHORT
            ).show()
        }
        sleep(1000)
        publishProgress(25)
        sleep(1000)
        publishProgress(56)
        sleep(2000)
        publishProgress(100)
        sleep(500)
        "T"
    }.doInBackground() //or .doInForeground() # default it will be background task
        .onStart {
            textView.text = "Starting task"
        }.onEnd {
            textView.append("\n" + "Task Finished")
        }.onResult { result ->
            textView.append("\nResult $result")
        }.onError { error ->
            textView.append("\nError " + error.message)
        }.onProgress {
            textView.append("\nProgress ${it[0]}")
        }.then {
            Task {//Inner Task
                sleep(2000)
                publishProgress("Result of outer task is $it")
                sleep(2000)
                "CT"
            }.onStart {
                textView.append("\nStarting chained task")
            }.onEnd {
                textView.append("\nChained task Finished")
            }.onResult { result ->
                textView.append("\nChained task Result $result")
            }.onError { error ->
                textView.append("\nChained task Error " + error.message)
            }.onProgress {
                textView.append("\nChained task Progress ${it[0]}")
            }
        }.start()

Java 任务

new Task<>(task -> {//Outer Task
        Task.Foreground.start(() -> Toast.makeText(this, "This is how you can toast with Task", Toast.LENGTH_SHORT).show());

        task.sleep(1000);
        task.publishProgress(25);
        task.sleep(1000) //Function chaining is also possible
                .publishProgress(56)
                .sleep(2000)
                .publishProgress(100)
                .sleep(500);
        return "T2";
    })
    .doInBackground() //or .doInForeground() # default it will be background task
    .onStart(() -> textView.append("\nStarting task 2"))
    .onEnd(() -> textView.append("\n" + "Task 2 Finished"))
    .onResult(result -> textView.append("\nTask 2 " + result))
    .onError(error -> textView.append("\nTask 2 " + error.getMessage()))
    .onProgress(progress -> textView.append("\nTask 2 Progress " + progress[0]))
    .then(result ->
            new Task<>(t2 -> {//Inner Task
                t2.sleep(2000);
                t2.publishProgress("Result of outer task is " + result);
                t2.sleep(2000);
                return "Task 2 chained result";
            }).onEnd(() -> textView.append("\nChained task 2 finished")
            ).onProgress(progress -> textView.append("\nChained Task 2 Progress " + progress[0])
            ).onResult(result2 -> textView.append("\n" + result2)))
    .start();
© www.soinside.com 2019 - 2024. All rights reserved.