【问题标题】:Modify an AsyncTask method using a not deprecated module使用未弃用的模块修改 AsyncTask 方法
【发布时间】:2021-04-24 13:49:02
【问题描述】:

我有这个方法正在使用已弃用的模块 AsyncTask:

private void createNewNote() {
        AsyncTask<ContentValues, Void, Uri> task = new AsyncTask<ContentValues, Void, Uri>() {
            @Override
            protected Uri doInBackground(ContentValues... params) {
               ContentValues insertValues = params[0];
               Uri rowUri = getContentResolver().insert(Notes.CONTENT_URI, insertValues);
               return rowUri;
            }
            @Override
            protected void onPostExecute(Uri uri) {
                mNoteUri = uri;
            }
        };

        ContentValues values = new ContentValues();
        values.put(Notes.COLUMN_COURSE_ID, "");
        values.put(Notes.COLUMN_NOTE_TITLE, "");
        values.put(Notes.COLUMN_NOTE_TEXT, "");

        task.execute(values);
    }

我想使用现代模块而不是 AsyncTask。我尝试使用

ExecutorService executor = Executors.newSingleThreadExecutor();

但问题是我需要将一个值从后台任务返回到主线程,而我没有设法用 newSingleThreadExecutor 做到这一点。你有什么解决办法? (我想让事情尽可能接近实际解决方案)。

【问题讨论】:

  • 这是安卓版吗?然后也许检查stackoverflow.com/questions/58767733/… ...否则,看看诸如期货之类的概念(baeldung.com/java-future
  • 是的,我实际上检查了这个问题。但这里的区别是我在 doInBackground 和 onPostExecute 之间传递了一个值
  • 你还没有说你是不是专门要求安卓的。
  • 对不起,是的,我会更新问题

标签: java android asynchronous


【解决方案1】:

您可以在 Kotlin 中使用 Coroutinessuspend 函数。

suspend fun fetchData(): YourResponse {
     // make network call
     // return your response
}

然后你可以像这样在活动或片段中使用:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    GlobalScope.launch(Dispatchers.Main) {
        val data = fetchData() // fetch on IO thread
        showData(data) // back on UI thread
    }
    
}

Dispatchers.Main UI 线程中的句柄。 如果你熟悉 MVVM 可以使用 ViewModel,你可以使用 viewmodelscope.launch 并使用 LiveData 监听数据变化

欲了解更多信息:https://developer.android.com/kotlin/coroutines

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多