Activity & Intent Bok, Jong Soon Jongsoon.bok@gmail.com www.javaexpert.co.kr
4 Components Activity Service Broadcast Receiver Content Provider
Android Application Structure View View Activity Service Broadcast Receiver Control Model SQLite File
Activity Android 응용프로그램을구성하는 4 가지컴포넌트중하나 Is an application component that provides a screen with which users can interact in order to do something. Each activity is given a window in which to draw its user interface. 독립된기능을수행하며, 서로중첩되지않음
Activity (Cont.)
Activity (Cont.) Creating an Activity To create an activity, must create a subclass of Activity. In your subclass, need to implement callback methods that the system calls. When the activity transitions between various states of its lifecycle : Is being created, stopped, resumed, or destroyed.
Activity (Cont.) Creating an Activity The two most important callback methods are: oncreate() Must implement this method. Must call setcontentview() to define the layout for the activity's user interface. onpause() The system calls that the user is leaving your activity.
Activity (Cont.) Implementing a user interface 화면하나에대응되며입출력기능이없어내부에 View 또는 ViewGroup 을가져야함
Activity (Cont.) Declaring the activity in the manifest To declare, open your manifest file and add an <activity> element as a child of the <application> element.
Lab1 : Activity Themes 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), p.143.
Lab1 : Activity Themes (Cont.) AndroidManifest.xml
Lab1 : Activity Themes (Cont.) settheme()
Lab1 : Activity Themes (Cont.) setflags()
android.view.window constants
Lab2 : Activity Themes (Cont.) 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), p.146.
Lab2 : Activity Themes (Cont.)
Lab3 : Activity Themes (Cont.) 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), p.147.
Lab3 : Activity Themes (Cont.)
Lab4 : Activity Themes (Cont.) 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), p.148.
Lab4 : Activity Themes (Cont.)
Lab5 : Activity Themes (Cont.) 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), p.149.
Lab5 : Activity Themes (Cont.) theme1.xml
Activity (Cont.) Starting an Activity Can start another activity by calling startactivity(), passing it an Intent. Can do so by creating an intent that explicitly defines the activity you want to start, using the class name.
Activity (Cont.) Shutting Down an Activity Can shut down an activity by calling its finish() method. Can also shut down a separate activity that you previously started by calling finishactivity().
LifeCycle An activity can exist in essentially three states: Resumed(Running) The activity is in the foreground of the screen and has user focus. Paused Another activity is in the foreground and has focus. But this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. A paused activity is completely alive. The Activity object is retained in memory, it maintains all state and member information, and remains attached to the window manager. But can be killed by the system in extremely low memory situations.
LifeCycle (Cont.) An activity can exist in essentially three states: Stopped The activity is completely obscured by another activity. The activity is now in the "background. A stopped activity is also still alive. The Activity object is retained in memory, it maintains all state and member information. But is not attached to the window manager. However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere. If an activity is paused or stopped, the system can drop it from memory either by asking it to finish.
LifeCycle (Cont.)
LifeCycle (Cont.)
LifeCycle (Cont.) Method Description Next Method oncreate() Called when the activity is first onstart() created. This is where you should do all of your normal static set up. onrestart() Called after the activity has onstart() been stopped, just prior to it being started again. onstart() Called just before the activity becomes visible to the user. onresume() or onstop() onresume() Called just before the activity onpause() starts interacting with the user.
LifeCycle (Cont.) Method Description Next Method onpause() onstop() Called when the system is about to start resuming another activity. Called when the activity is no longer visible to the user. onresume() or onstop() onrestart() or ondestroy() ondestroy() Called before the activity is destroyed. This is the final call that the activity will receive. It could be called either because the activity is finishing or because the system is temporarily destroying this instance of the activity to save space. nothing
LifeCycle (Cont.) Can monitor three nested loops in the activity lifecycle: The entire lifetime Between the call to oncreate() and the call to ondestroy(). Your activity should perform setup of "global" state (such as defining layout) in oncreate(), and release all remaining resources in ondestroy(). The visible lifetime Between the call to onstart() and the call to onstop(). During this time, the user can see the activity on-screen and interact with it. The system might call onstart() and onstop() multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user. The foreground lifetime Between the call to onresume() and the call to onpause(). During this time, the activity is in front of all other activities on screen and has user input focus.
Lab6 : Activity LifeCycle 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), pp.154-155.
Lab6 : Activity LifeCycle (Cont.)
Lab7 : onsavedinstancestate() 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), p.156.
Lab7 : onsavedinstancestate()(cont.)
Adding Activity 보안상의이유로응용프로그램에포함된모든 Activity 는반드시 manifest 에등록 Manifest 에등록되지않은 Activity 는존재하지않는것으로취급 Main 에서 Call 버튼을눌러 SubActivity 를호출할때 startactivity () 가 SubActivity 를찾지못하여 Exception 이발생하며다운 Manifest 에 SubActivity 등록
Adding Activity (Cont.) <activity android:name=.callactivity" android:label="callactivity" /> <activity android:name=.subactivity" android:label="subactivity" /> </application> <uses-sdk android:minsdkversion= 15" /> </manifest> Activity 의이름과 Title Bar 에표시할제목은최소한지정 Activity 의이름은 package 명을포함한전체경로로지정하되같은 package 에속해있을때는앞에. 을넣음. [ 액티비티추가예제최종결과 ]
Lab8 : Adding Activity 김상형, 안드로이드프로그래밍정복개정판 1 권 ( 서울 : 한빛미디어, 2011), pp.732-736.
Lab8 : Adding Activity (Cont.)
Lab8 : Adding Activity (Cont.)
Intent Android 의 Component 끼리통신하기위한 Message System. Activity 및 Component 사이의수행할작업에대한정보및작업결과리턴을위해서도사용 메인 Activity 혼자작업을수행하지않고다른 Activity 를호출하여일을분담 cf) Calling method
Intent (Cont.) Intent 객체의구성요소 Action Data Category Type Component Name Extras
Intent (Cont.) Action 수행할 동작 또는획득한정보나보고될행동을나타내는문자열 액션 대상 설명 ACTION_CALL Activity 통화시작. ACTION_EDIT Activity 데이터표시및편집한다. ACTION_MAIN Activity 메인 Activity 실행. ( 입출력데이터없음 ) ACTION_VIEW Activity 뭔가를보여줌. ACTION_DIAL Activity 전화를건다. ACTION_BATTERY_LOW BR 배터리부족. ACTION_HEADSET_PLUG BR 헤드셋이장비에접속또는분리됨. ACTION_SCREEN_ON BR 화면켜짐. ACTION_TIMEZONE_CHANGED BR 타임존변경.
Intent (Cont.) Category 실행할액션에대한추가정보를제공 addcategory, removecategory : 카테고리추가, 제거 카테고리 의미 android.intent.category.home 홈화면을표시하는 Activity 입니다. android.intent.category.launcher Activity 가 Application Launcher 에표시되며, Task 의첫 Activity 가될수있습니다. android.intent.category.preference 환경설정을표시하는 Activity 입니다.
Intent (Cont.) Data 동작에필요한상세데이터를제공하며, 단독액션의경우별도의 Data 가필요하지않고, 그외의액션은목적어에해당하는정보인데이터가필요 대상의종류가광범위하여임의의대상을가리킬수있는 URI 타입 getdata, setdata : 데이터액세스시사용 종류형태타입 (MIME) 의미 URL http://www.google.com URL 미디어 ( 사진 /JPEG) content://media/external/images/media/1 image/jpeg 이미지 미디어 ( 음악 /mp3) content://media/external/images/audio/1 audio/mp3 오디오 전화번호 tel:1234567 전화번호 좌표 geo:37.422006,-122.084095 특정지역 좌표
Intent (Cont.) Type 대부분자동으로판별가능 gettype, settype : 타입이애매하거나자동판별을신뢰할수없는경우데이터의 MIME 타입지정 데이터종류 mp3 오디오 mp4 비디오 jpeg 이미지콘텐트프로바이더제공컨텐츠 타입 (MIME) audio/mp3 video/mp4 image/jpeg vnd.android.cursor.dir/vnd.google.note
Intent (Cont.) Component Intent 를처리할 Component 를명시적으로지정 속성사용시다른정보를참조하지않음 Extras 그외 Component 로전달되어야할추가적인정보 putextra, getintextra, getstringextra Flags Activity 를띄울방법이나 Activity 관리방법등의옵션정보들이저장 setflag flag 전체대입 addflags 특정 flag 추가로지정
Intent s Constructor Intent (Cont.)
Intent (Cont.) Intent s Constructor 실행중에액티비티를생성해야하므로클래스정보가필요 예제 (Lab8) 의호출문 Intent intent = new Intent(this, SubActivity.class); startactivity(intent); 호출자 : MainActivity 자신 호출대상 : SubActivity startactivity() : Intent 의정보를참조하여 MainActivity 를부모로하는 SubActivity 를호출
Intent (Cont.) Intent 의종류 Explicit intent Intent 에호출할대상 Component 가분명히명시 주로같은응용프로그램내의 Sub Activity 를호출할때사용 권한에따라외부응용프로그램의 Activity 도호출가능 Implicit intent 호출대상이분명히정해지지않은 Intent 주로다른응용프로그램의 Component 를호출할때사용 호출할대상을정확히찾을수있도록상세한정보가적성되어야함 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(tel:1112223333)); startactivity(intent);
Intent (Cont.) http://developer.android.com/guide/appendi x/g-app-intents.html
Lab9 : Implicit Intent 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), pp.411-413.
Lab9 : Implicit Intent (Cont.)
Lab10 : Implicit Intent 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), pp.414-416.
Lab10 : Implicit Intent (Cont.)
Lab11 : Implicit Intent 손수국 조승호공저, 안드로이드프로그래밍의이해와실제 ( 경기 : 생능출판사, 2010), pp.263-267.
Lab11 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.) 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), pp.430-439.
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Lab12 : Implicit Intent (Cont.)
Intent (Cont.) Activity 사이의통신 Intent 는 Activity 간에인수와리턴값을전달하는도구로도이용 Bundle 타입의 Extras 를활용하며이름과값의쌍으로된임의타입의정보를원하는개수만큼전달가능 Extras 에값을저장하는메서드 거의모든타입에대해오버로딩되어있음 Intent putextra (String name, int value) Intent putextra (String name, String value) Intent putextra (String name, boolean value) name : 전달하는인수의이름이며, 중복되지않으면자유롭게지정가능
Intent (Cont.) Activity 사이의통신 Extras 에저장된값은아래의메서드로꺼냄 int getintextra (String name, int defaultvalue) String getstringextra (String name) Boolean getbooleanextra (String name, boolean defaultvalue) 값이전달되지않았을경우두번째인수로지정한디폴트가리턴, 문자열은 null 이리턴 입력뿐아니라리턴값을돌려줄때사용가능하며, 적당한이름으로값을넣어두면호출원에서약속된이름으로리턴값을꺼내사용
Intent (Cont.) Activity 를통한값전송및리턴처리하기 인수와리턴값 : Intent 를통해전달 호출을요청한대상에대한정보가포함되어야함 리턴값을돌려주는 Activity 는아래의 method 로호출 public void startactivityforresult (Intent intent, int requestcode) 두번째인수 : 호출한대상을나타내는식별자, 리턴시에누구에대한리턴인가를구분 호출되는 Activity 별로고유의번호를붙여야하며, 0 이상의중복되지않는정수를넘기며, 음수일경우리턴받지않음
Intent (Cont.) Activity 를통한값전송및리턴처리하기 호출된 Activity 가종료후아래의 method 호출 protected void onactivityresult (int requestcode, int resultcode, Intent data) 리턴값을받으려면 method 를재정의 requestcode : Activity 를호출할때전달한요청코드 resultcode : Activity 의실행결과 리턴값은 data Intent 안에포함되어있으므로 data 안에 Extras 를읽어구할수있음
Lab12 : Explicit Intent 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), pp.417-422.
Lab12 : Explicit Intent (Cont.)
Lab13 : Explicit Intent 한동호, 단계별예제로배우는안드로이드프로그래밍 ( 경기 : 제이펍, 2011), pp.423-429.
Lab13 : Explicit Intent (Cont.)
Lab14 : Explicit Intent 손수국 조승호공저, 안드로이드프로그래밍의이해와실제 ( 경기 : 생능출판사, 2010), pp.268-274.
Lab14 : Explicit Intent (Cont.)
Lab14 : Explicit Intent (Cont.)
Lab14 : Explicit Intent (Cont.)
Lab14 : Explicit Intent (Cont.)
Intent (Cont.) Intent Filter Component 에대한 Intent 정보를말하며, Component 가어떤 Action 과 Data 를처리할수있는지에대한정보를기술 응용프로그램의 manifest 에기록 운영체제가 Intent Filter 를검색하는알고리즘은상세히공개되어있으며, 점수제 1 순위 : 액션과카테고리의일치성 2 순위 : 데이터의일치성 여러개가검색될경우일치도가가장높은것을선택, 빌트인과써드파티응용프로그램에대한차별은없음
Intent (Cont.) Intent Filter Intent filter 를정의할때에주로필터링하는항목은 action, data, category 이다. action 서비스되는액션의이름. 유일한문자열이어야한다. i.e. android.intent.action.dial
Intent (Cont.) Intent Filter category : 액션이서비스돼야하는상황을지정 android.intent.category.alternative android.intent.category.selected_alternative android.intent.category.browsable android.intent.category.default android.intent.category.garget android.intent.category.home android.intent.category.launcher 기본액션에대한대안액션임을선언 대안으로선택가능한것들에대한선언 브라우져안에서사용가능한액션지정 데이터값에대한기본액션으로지정 이액티비티가다른액티비티내부에포함되어동작할수있도록지정 네이티브홈스크린의대안 애플리케이션런쳐
Lab15 : Intent Filter 김상형, 안드로이드프로그래밍정복개정판 1 권 ( 서울 : 한빛미디어, 2011), pp.751-753.
Lab15 : Intent Filter (Cont.)
Lab15 : Intent Filter (Cont.)
Lab15 : Intent Filter (Cont.)