Android 기본 사항: UI 스레드에서 코드 실행
UI 스레드에서 코드를 실행하는 관점에서 다음과 같은 차이점이 있습니까?
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
또는
MainActivity.this.myView.post(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
그리고.
private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {
protected void onPostExecute(Bitmap result) {
Log.d("UI thread", "I am the UI thread");
}
}
이들 중 어느 것도 정확히 동일하지는 않지만, 모두 동일한 순 효과를 가질 것입니다.
첫 번째와 두 번째의 차이점은 코드를 실행할 때 메인 응용 프로그램 스레드에 있을 경우 첫 번째 스레드(runOnUiThread())이 실행됩니다.Runnable즉시두 번째 (post()) 항상 다음과 같이 배치합니다.Runnable사용자가 이미 기본 응용 프로그램 스레드에 있는 경우에도 이벤트 대기열의 끝에 있습니다.
세 번째는, 당신이 다음의 인스턴스를 만들고 실행한다고 가정합니다.BackgroundTask기본 no-op을 실행하기 위해 스레드 풀에서 스레드를 가져오는 데 많은 시간을 낭비합니다.doInBackground()결국에 그것에 해당하는 것을 하기 전에.post()이것은 세 가지 중에서 훨씬 덜 효율적입니다.사용하다AsyncTask단순히 사용을 위한 것이 아니라 실제로 백그라운드 스레드에서 해야 할 일이 있는 경우.onPostExecute().
저는 HPP 댓글에 있는 것이 마음에 들어요, 그것은 매개 변수 없이 어디서나 사용할 수 있습니다.
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
사용하는 네 번째 방법이 있습니다.
new Handler().post(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});
폼버의 대답은 받아들일 수 있지만, 저는 반복적으로 새로운 물체를 만드는 것을 좋아하지는 않습니다.가장 좋은 해결책은 항상 메모리 부족을 완화하는 것입니다.예, 자동 가비지 수집이 있지만 모바일 장치의 메모리 보존은 모범 사례의 범위 내에 있습니다.아래 코드는 서비스의 TextView를 업데이트합니다.
TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
private String txt;
@Override
public void run() {
searchResultTextView.setText(txt);
}
public void setText(String txt){
this.txt = txt;
}
}
다음과 같은 장소에서 사용할 수 있습니다.
textViewUpdater.setText("Hello");
textViewUpdaterHandler.post(textViewUpdater);
Android P 기준으로 사용할 수 있습니다.getMainExecutor():
getMainExecutor().execute(new Runnable() {
@Override public void run() {
// Code will run on the main thread
}
});
Android 개발자 문서:
이 컨텍스트와 연결된 주 스레드에서 대기열에 있는 작업을 실행할 실행자를 반환합니다.이 스레드는 응용 프로그램 구성 요소(활동, 서비스 등)에 호출을 발송하는 데 사용됩니다.
Commons 블로그에서:
컨텍스트에서 getMainExecutor()를 호출하여 기본 응용 프로그램 스레드에서 작업을 실행할 Executor를 가져올 수 있습니다.Looper 및 사용자 정의 Executor 구현을 사용하여 이를 수행하는 다른 방법도 있지만, 이 방법이 더 간단합니다.
fragment에서 사용해야 하는 경우 사용해야 합니다.
private Context context;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
((MainActivity)context).runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
대신에
getActivity().runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
호출기 조각과 같은 일부 상황에서는 null 포인터 예외가 발생하기 때문입니다.
처리기 사용
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});
코틀린 버전:
Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "Running on UI(Main) thread.", Toast.LENGTH_LONG).show()
}
또는 코틀린 코루틴을 사용하는 경우: 코루틴 범위 내에 다음을 추가합니다.
withContext(Dispatchers.Main) {
Toast.makeText(context, "Running on UI(Main) thread.", Toast.LENGTH_LONG).show()
}
언급URL : https://stackoverflow.com/questions/12850143/android-basics-running-code-in-the-ui-thread
'programing' 카테고리의 다른 글
| 요청 본문 유형을 요청과 호환되도록 만드는 방법Initior Body노드 페치를 사용할 때 초기화? (0) | 2023.06.08 |
|---|---|
| 저장 프로시저에서 이 Oracle SQL Developer 아이콘은 무엇을 의미합니까? (0) | 2023.06.08 |
| 포드 설정을 실행하면 "잘못된 통역사:해당 파일 또는 디렉터리 없음" 오류 (0) | 2023.06.03 |
| web.config 파일을 사용하여 HTTPS를 강제 적용하는 방법 (0) | 2023.06.03 |
| wpf 창에 사용자 컨트롤 추가 (0) | 2023.06.03 |