본문

170925(월) - Android thread and Background task understanding

Android thread and Background task understanding


원문 : https://academy.realm.io/kr/posts/android-threading-background-tasks/?

책 추천 : http://shop.oreilly.com/product/0636920029397.do

API 추천 : https://developer.android.com/training/multiple-threads/index.html


Android thread

- Application class 가 생성될 때 함께 만들어진다.

- 주로 UI를 그리고, 사용자의 상호작용을 처리하고 화면에서 픽셀을 그리며 액티비티를 시작.

- Activity에 추가되는 코드는 UI thread가 끝난 이후 남아있는 thread로 실행


”각 스레드는 [스레드] 실행 중에 메서드 로컬 변수와 매개 변수를 저장하는데 주로 사용되는 독립용 메모리 영역을 할당합니다. 독립용 메모리 영역은 스레드가 생성될 때 할당되고, 스레드가 종료되면 할당이 해제됩니다.”

        • Anders Göransson, Efficient Android Threading


- Context switching

multi-thread 를 사용하면 다른 thread로 실행이 전환될 때마다 약간의 delay time이 발생한다.



AsyncTask

// AsyncTask.java
private static class InternalHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			AsyncTaskResult result = (AsyncTaskResult) msg.obj;
			switch (msg.what) {
				case MESSAGE_POST_RESULT:
					// There is only one result
					result.mTask.finish(result.mData[0]);
					break;
				case MESSAGE_POST_PROGRESS:
					result.mTask.onProgressUpdate(result.mData);
					break;
			}
		}
}

- AsyncTask 내부에 handler instance가 존재한다.

- 아래와 같은 javascript의 callback chaning은 지양한다.

new AsyncTask<Void, Void, Boolean>() {
	protected Boolean doInBackground(Void... params) {
		doOneThing();
		return null;
	}
	protected void onPostExecute(Boolean result) {
		AsyncTask doAnotherThing =
			new AsyncTask<Void, Void, Boolean>() {
			protected Boolean doInBackground(Void... params) {
				doYetAnotherThing();
				return null;
			}
			private void doYetAnotherThing() {}
		};
		doAnotherThing.execute();
	}
	private void doOneThing() {}
}.execute();

- 위와같은 코드는 끔직하며, 이러한 설계는 반드시 피해야 한다.

- IntentService로 해결 가능!



IntentService

- 다른 thread가 실행되고 android 환경을 유지 관리

- UI thread과 독립적으로 실행되며, application이 맨 앞이 아닐때도 실행 가능.

- 해당 thread를 시작하고 닫는것을 신경쓰지 않아도 된다.

- AsyncTask 보다 무겁고 작업하기 힘드며, 설정이 더 많이 필요하고 Manifest도 변경이 필요하다.

- Intent Bundle에 데이터 전달이 용이

android-threading-signal

CodePath 가이드를 반드시 읽어볼 것.

// Activity
ResultReceiver rr = new
ResultReceiver() {
	@Override
	onReceiveResult() {
		// do stuff!
	}
}
// add rr to extras
startService(myServiceIntent);

// Service
onHandleIntent(Intent i) {
	ResultReceiver rr =
	i.getExtras().get(RR_KEY)
	(assigned from bundle)

	rr.send(Activity.RESULT_OK
	successData);
}


'Mobile > Android' 카테고리의 다른 글

170706(목) - InputMethodManager.isAcceptingText()  (0) 2017.07.06
170627(화) - Map  (0) 2017.06.27
160510A(화)  (0) 2016.05.10
160504A(수)  (0) 2016.05.04
160405A(화)  (0) 2016.04.05

공유

댓글