【问题标题】:Run the tasks in background ( AsyncTask )在后台运行任务( AsyncTask )
【发布时间】:2020-10-24 21:47:05
【问题描述】:

在 NoteInfoactivity 我下面有一个代码,但是

Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);

在主线程中执行。 如何在后台执行?最好的方法是什么?

public class NoteInfoActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_note_info);

    TextView textViewTitle = findViewById(R.id.textViewNoteTitle);
    TextView textViewPriority = findViewById(R.id.textViewPriority);

    Intent intent = getIntent();

    if (intent != null && intent.hasExtra("NoteID")) {
        long noteID = intent.getIntExtra("NoteID", -1);

        Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);

        String title = allNote.getTitle();
        int priority = allNote.getPriority();

        textViewTitle.setText(title);
        textViewPriority.setText(String.valueOf(priority));
        
    } else {
        Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_SHORT).show();
    }
}

}

【问题讨论】:

  • 这能回答你的问题吗? AsyncTask Android example
  • 使用实时数据对象从 room dao 获取数据的最佳方法,观察新数据插入或更新时的变化

标签: android multithreading android-asynctask background-thread


【解决方案1】:

您可以将它放在一个线程中,然后调用处理程序在主线程上进行 UI 更改。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_note_info);

    TextView textViewTitle = findViewById(R.id.textViewNoteTitle);
    TextView textViewPriority = findViewById(R.id.textViewPriority);

    Intent intent = getIntent();
    Handler handler = new Handler();

    if (intent != null && intent.hasExtra("NoteID")) {
        long noteID = intent.getIntExtra("NoteID", -1);
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);
                handler.post((Runnable) () -> {
                    String title = allNote.getTitle();
                    int priority = allNote.getPriority();

                    textViewTitle.setText(title);
                    textViewPriority.setText(String.valueOf(priority));
                });
            }
        }).start();
    } else {
        Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_SHORT).show();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2013-10-01
    • 2016-09-05
    • 2015-05-05
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多