CHAP 14. 프로세스와 스레드. © 2012 생능출판사 All rights reserved 다중 스레딩 하나의 애플리케이션이 동시에 여러 가지 작업을 하 는 것 이들 작업은 스레드 (thread) 라고 불린다.

Slides:



Advertisements
Similar presentations
Threads, AsyncTasks & Handlers.  Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process.
Advertisements

The Activity Class 1.  One application component type  Provides a visual interface for a single screen  Typically supports one thing a user can do,
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
User Interface Android Applications. Activities An activity presents a visual user interface. Each activity is given a default window to draw in. The.
Android Application Development with Java UPenn CS4HS 2011 Chris Murphy
@2011 Mihail L. Sichitiu1 Android Introduction Hello World.
Android Application Development Tutorial. Topics Lecture 5 Overview Overview of Networking Programming Tutorial 2: Downloading from the Internet.
1 Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources, Listener 10/9/2012 Y. Richard Yang.
Cosc 5/4730 A little on threads and Messages: Handler class.
Android Tutorial Team 3 Jerry Yu Mayank Mandava Mu Du Will Wangles.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
안드로이드 프로그래밍 서비스와 방송 수신자 장 원 영 실습파일 :
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
CHAP 10. 고급 위젯. © 2012 생능출판사 All rights reserved 어댑터 뷰 어댑터 뷰 (AdapterView) 는 배열이나 파일, 데이터 베이스에 저장된 데이터를 화면에 표시할 때 유용한 뷰.
로봇 전화번호부 4/4 UNIT 12 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 뷰 홀더 패턴을 사용할 수 있다. 토스트를 사용할 수 있다. 클릭 이벤트를 처리할 수 있다. 2.
Android Programming-Activity Lecture 4. Activity Inside java folder Public class MainActivity extends ActionBarActivity(Ctrl + Click will give you the.
Threads and Services. Background Processes One of the key differences between Android and iPhone is the ability to run things in the background on Android.
Import import android.graphics.Bitmap; import android.widget.ImageView;
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
Activity 생명주기 UNIT 13 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Logcat 액티비티 생명주기를 설명할 수 있다. 현재 상태를 저장할 수 있다. 2.
1 Introducing Activity and Intent. 2 Memory LinearLayout, weight=2 LinearLayout, weight=1 TextView ListView.
ANDROID – DRAWING IMAGES – SIMPLE EXAMPLE IN INTERFACE AND EVENT HANDLING L. Grewe.
데이터 저장 & Fragment UNIT 28 로봇 SW 콘텐츠 교육원 조용수. 데이터 저장 & Fragment SharedPreference 로 데이터 저장 Fragment 의 이해 2.
Announcements Homework #2 will be posted after class due Thursday Feb 7, 1:30pm you may work with one other person No office hours tonight (sorry!) I will.
Android Using Menus Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © CommonsWare, LLC. ISBN:
Android Threads. Threads Android will show an “ANR” error if a View does not return from handling an event within 5 seconds Or, if some code running in.
CHAP 11. 액티비티와 인텐트.
CHAP 8. 고급 그래픽과 O PEN GL. © 2012 생능출판사 All rights reserved C ANVAS 클래스와 P AINT 클래스.
CHAP 8. 그래픽.
네트워크 전송 1/2 UNIT 29 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Android Network 통신 2.
Android Application Lifecycle and Menus
로봇을 조종하자 4/4 UNIT 18 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Intent Activity 호출 2.
Android and s Ken Nguyen Clayton state University 2012.
아주대학교 LifecareScienceLAB Android Seminar 3 rd class Android Software Development 2011/05/04 – p.m. 06:00 – 팔달관 409 호 아주대학교.
로봇을 조종하자 1/5 UNIT 14 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 터치 이벤트를 처리할 수 있다. 2.
Mobile Computing Lecture#12 Graphics & Animation.
User Interface Layout Interaction. EventsEvent Handlers/Listeners Interacting with a user.
Android Alert Dialog. Alert Dialog Place Button to open the dialog. public class MainActivity extends ActionBarActivity { private static Button button_sbm;
CHAP 6. 이벤트 처리. © 2012 생능출판사 All rights reserved 폴링과 이벤트 구동 방식.
CHAP 7. 메뉴와 대화상자. © 2012 생능출판사 All rights reserved 메뉴의 종류 옵션 메뉴 : 사용자가 MENU 키를 누를 때 나타난다. 컨텍스트 메뉴 : 컨텍스트 메뉴는 사용자가 화면을 일정 시간 이상으로 길게 누르면 나타나는 메뉴이다.
© 2012 생능출판사 All rights reserved CHAP 8. 그래픽. © 2012 생능출판사 All rights reserved 안드로이드에서의 2 차원 그래픽 사용 방법 1) XML 파일로 그래픽이나 애니메이션을 정의한다. 그리는 작업은 안드로이드 시스템이.
Android 基本 I/O. 基本 I/O 介面元件 在此節中主要介紹常見的 I/O 使用者介 面元件 – Button, TextView, 以及 EditText , 學習者可以學會: – Android 的視窗表單設計 res/layout/main.xml – Android SDK –
CHAP 8. 그래픽. © 2012 생능출판사 All rights reserved 안드로이드에서의 그래픽 XML 파일로 그래픽이나 애니메이션을 정의한다. 그 리는 작업은 안드로이드 시스템이 담당한다. onDraw() 메소드 안에 draw...() 와 같은 메소드를 호.
Concurrency in Android
Lecture 3 Zablon Ochomo Android Layouts Lecture 3 Zablon Ochomo
Android Introduction Hello World
GUI Programming Fundamentals
Android Multi-Threading
CS499 – Mobile Application Development
Android – Event Handling
Concurrency in Android
Android Introduction Hello World.
CS499 – Mobile Application Development
ITEC535 – Mobile Programming
CS499 – Mobile Application Development
תכנות ב android אליהו חלסצ'י.
Android Introduction Hello Views Part 2.
CIS 470 Mobile App Development
CIS 470 Mobile App Development
null, true, and false are also reserved.
BMI Android Application will take weight and height from the users to calculate Body Mass Index (BMI) with the information, whether user is underweight,
Lesson 11 Concurrency Control Victor Matos Cleveland State University
CIS 470 Mobile App Development
CIS 470 Mobile App Development
Threads, Handlers, and AsyncTasks
Adding Components to Activity
Android Threads Dimitar Ivanov Mobile Applications with Android
Android Sensor Programming
Android Sensor Programming
Presentation transcript:

CHAP 14. 프로세스와 스레드

© 2012 생능출판사 All rights reserved 다중 스레딩 하나의 애플리케이션이 동시에 여러 가지 작업을 하 는 것 이들 작업은 스레드 (thread) 라고 불린다.

© 2012 생능출판사 All rights reserved 안드로이드에서의 프로세스와 스레드 애플리케이션이 시작되면 안드로이드 시스템은 새 로운 리눅스 프로세스를 생성한다. 기본적으로 애플리케이션 안의 모든 컴포넌트들은 동일한 프로세스의 동일한 스레드로 실행된다. 이 기본적인 스레드를 메인 스레드 (main thread) 라 고 부른다.

© 2012 생능출판사 All rights reserved 메인 스레드 메인 스레드는 사용자 인터페이스 위젯에게 이벤트 를 전달하거나 화면을 그리는 작업을 담당 UI 스레드 (user interface thread) 라고도 불린다.

© 2012 생능출판사 All rights reserved 안드로이드의 단일 스레드 모델 원칙 UI 스레드는 블록시키면 안된다. UI 스레드 외부에서 안드로이드 UI 툴킷을 조작하면 안된다.

© 2012 생능출판사 All rights reserved 작업 스레드 별도로 생성되는 스레드 배경 스레드 ("background" thread) 라고도 한다.

© 2012 생능출판사 All rights reserved 작업 스레드를 작성하는 방법 Thread 클래스를 상속받아서 스레드를 작성하는 방 법 Runnable 인터페이스를 구현한 후에 Thread 객체 에 전달하는 방법

© 2012 생능출판사 All rights reserved T HREAD 상속방법... public class ThreadTest extends Activity { WorkerThread w; boolean running = true; class WorkerThread extends Thread { public void run() { int i = 0; for (i = 0; i < 20 && running i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { } Log.v("THREAD", "time=" + i); }

© 2012 생능출판사 All rights reserved T HREAD 상속방법 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); public void onStart() { super.onStart(); w = new WorkerThread(); running = true; w.start(); public void onStop() { super.onStop(); running = false; }

© 2012 생능출판사 All rights reserved 실행 결과

© 2012 생능출판사 All rights reserved R UNNABLE 인터페이스를 구현 방법... public class ThreadTest extends Activity { Thread w; boolean running = public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }

© 2012 생능출판사 All rights reserved public void onStart() { super.onStart(); w = new Thread(new Runnable() { public void run() { int i = 0; for (i = 0; i < 20 && running i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { } Log.v("THREAD", "time=" + i); } }); running = true; w.start(); } public void onStop() { super.onStop(); running = false; }

© 2012 생능출판사 All rights reserved 실행결과

© 2012 생능출판사 All rights reserved public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork(" mImageView.setImageBitmap(b); } }).start(); } 주의할 점 스레드에서 직접적으로 사용자 인터페이스 위젯을 변경하면 안 된다.

© 2012 생능출판사 All rights reserved 해결할 수 있는 3 가지 방법 Activity.runOnUiThread(Runnable) View.post(Runnable) View.postDelayed(Runnable, long)

© 2012 생능출판사 All rights reserved V IEW. POST (R UNNABLE ) 사용 public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork(" mImageView.post(new Runnable() { public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start(); }

© 2012 생능출판사 All rights reserved H ANDLER 사용 class WorkerThread extends Thread { Handler handler; WorkerThread(Handler handler) { this.handler = handler; } public void run() { for (int i = 0; i < 20; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { } Message msg = new Message(); msg.what = 1; msg.arg1 = i; handler.sendMessage(msg); }

© 2012 생능출판사 All rights reserved H ANDLER 사용... public class HandlerTest extends Activity { WorkerThread thread; TextView text; Handler handler; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (TextView) findViewById(R.id.text); handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 1) { text.setText(" 카운터 =" + msg.arg1); } thread = new WorkerThread(handler); thread.start(); }

© 2012 생능출판사 All rights reserved 실행 결과

© 2012 생능출판사 All rights reserved H ANDLER 클래스를 사용하는 방법 러너블 객체를 UI 스레드로 보낼 수 있다.

© 2012 생능출판사 All rights reserved 사용자 인터페이스 작성 <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" /> <ProgressBar android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal">

© 2012 생능출판사 All rights reserved 액티비티 작성... public class ProgressBarTest extends Activity { private static final int PROGRESS = 0x1; private ProgressBar mProgress; private int mProgressStatus = 0; int i = 0; protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mProgress = (ProgressBar) findViewById(R.id.progress_bar); //

© 2012 생능출판사 All rights reserved 액티비티 작성 new Thread(new Runnable() { public void run() { while (mProgressStatus < 100) { try {Thread.sleep(1000);} catch (InterruptedException e) {} mProgressStatus = i++; // mProgress.post(new Runnable() { public void run() { mProgress.setProgress(mProgressStatus); } }); } }).start(); }

© 2012 생능출판사 All rights reserved 실행 결과

© 2012 생능출판사 All rights reserved A SYNC 클래스 사용 방법 AsyncTask 클래스는 1.5 버전부터 추가된 클래스로 서 작업 스레드와 관련된 복잡한 부분을 쉽게 처리 해주는 클래스

© 2012 생능출판사 All rights reserved 예제... public class AsyncTest extends Activity { private ProgressBar mProgress; private int mProgressStatus = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mProgress = (ProgressBar) findViewById(R.id.progress_bar); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { new CounterTask().execute(0); } }); }

© 2012 생능출판사 All rights reserved class CounterTask extends AsyncTask { protected void onPreExecute() {} protected Integer doInBackground(Integer... value) { while (mProgressStatus < 100) { try {Thread.sleep(1000);} catch (InterruptedException e) {} mProgressStatus++; publishProgress(mProgressStatus); } return mProgressStatus; } protected void onProgressUpdate(Integer... value) { mProgress.setProgress(mProgressStatus); } protected void onPostExecute(Integer result) { mProgress.setProgress(mProgressStatus); }

© 2012 생능출판사 All rights reserved 실행 결과