运行 后台任务 (AsyncTask)

Run the tasks in background ( AsyncTask )

在 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();
    }
}

}

您可以将它放在一个线程中,然后调用处理程序在主线程上执行 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();
    }
}