brunch

You can make anything
by writing

C.S.Lewis

by 이승현 May 30. 2016

안드로이드 면접 질문 #03

Android interview questions

Skillgun


Android activities/services interview questions and answers


http://skillgun.com/android/activities/interview-questions-and-answers/paper/13



Activity


Question #01

Explain the life cycle of an activity, in android?

(Activity의 생명주기?)

                              

   

Answer

onCreate-> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()


onCreate()

1. The system calls this when creating your activity.

(activity를 생성할 때 호출한다.)


2. You should initialize the essential components of your activity. Eg:setcontentview.

setContentView와 같은 필수적인 구성요소를 초기화해야 한다.


3. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

(super.onCreate(savedInstanceState) 반드시 호출해야 한다.)


onStart()

1. Called after onCreate(Bundle) or after onRestart() followed by onResume().

(onCreate(Bundle) 또는 onRestart() 이후에 호출되고 다음에는 onResume이 불린다.)


2. you can register a BroadcastReceiver in onStart() to monitor changes that impact your UI, You have to unregister it in onStop().

(UI에 영향을 주는 변화를 감지하기 위해 BroadcastReceiver를 등록할 수 있다. 그리고 onStop()에서 반드지 해제시켜줘야 한다.)


3. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

(super.onStart() 반드시 호출해야 한다.)


onResume()

1. Called after onRestoreInstanceState(Bundle), onRestart(), or onPause().

(nRestoreInstanceState(Bundle), onRestart(), onPause() 다음에 호출된다.)


2. begin animations, open exclusive-access devices (such as the camera).

(시작 애니메이션, 카메라 같은 exclusive-access 디바이스를 오픈.)


onPause()

1. Called as part of the activity lifecycle when an activity is going into the background.

(activity가 background로 갈 때 activity 생명 주기의 일환으로 호출된다.)


2. The counterpart to onResume().

(onResume()와 짝? 상대적?이다.)


3. B will not be created until A's onPause() returns. (So don’t do anything long here.

(A의 onPause()가 리턴될 때까지 B는 생성되지 않는다. 따라서 시간이 오래 걸리는 일은 여기서 하지 마라.)


4. Save all your persistent data here.

(영구적인 data는 모두 여기서 저장.  메모리 부족 같은 경우엔 onStop()을 거치지 않을 수 있기 때문.)


5. Good place to do things like stop animations (any CPU consuming things), to make switching to other activity as soon as possible.

(가능한 한 빨리 다른 activity로 전환하기 위해 애니메이션 정지와 같은 CPU를 많이 소비하는 일들은 여기서 정지하기 좋다.)


6. Eg: if device goes to sleep or some dialog is displayed, then it will go to onPause().

(디바이스가 잠들거나 다른 다이얼로그가 표시되면 onPause()로 간다. (카톡 메시지가 와도 onPause.))


7. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

(super.onPause() 반드시 호출해야 한다.)


onStop()

1. Called when you are no longer visible to the user

(더 이상 사용자들이 볼 수 없을 때 호출된다.)


2. You will next receive either onRestart(), onDestroy()

(다음으로 onRestart()나 onDestroy()가 호출된다.)


3. this method may never be called, in low memory situations

(메모리 부족일 경우 절대 호출되지 않는다.)


4. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

(super.onStop() 반드시 호출해야 한다.)


onDestroy()

1. Perform any final cleanup before an activity is destroyed

(activity가 파괴되기 전에 최종 정리 작업을 수행한다.)


2. do not count on this method being called as a place for saving data!

(데이터를 저장하기 위해 이 메서드를 이용하지 마라!)


3. This method is usually implemented to free resources like threads that are associated with an activity.

(이 메서드는 일반적으로 activity와 관련된 스레드 같은 리소스들을 해제를 구현한다.)


4. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown

(super.onDestroy() 반드시 호출해야 한다.)


onRestart()

1. Called after onStop() when the current activity is being re-displayed to the user.

(현재 activity가 유저에게 다시 표시될 때 onStop()이 후에 호출된다.)


2. It will be followed by onStart() and then onResume().

(이후에 onStart() 그리고 onResume()이 호출된다.)


3. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

(super.onRestart() 반드시 호출해야 한다.)


Question #02

In Activity's onCreate function, What is the purpose of super.oncreate()?

(onCreate 함수에서 super.onCreate()을 쓰는 이유는?)

                              

   

Answer

Every activity should inherit from Activity class.

(모든 activity는 Activity 클래스로부터 상속한다.)


Activity base class provides 3 basic functions for every screen:

(Activity 기본 클래스는 모든 화면을 위해 3가지의 기본적인 함수를 제공한다.)


1. It provides empty graphical window on which you can load your designed screen.

(디자인된 화면을 로드할 수 있는 빈 그래픽 창을 제공한다.)


2. Activity Base Class will handle all the UI events which are not handled by programmer.

(프로그래머에 의해 처리되지 않는 UI 이벤트들을 처리한다.)

 

3. Activity Base Class will handle transition states of your activity, when you are moving from one activity to other activity. 

(다른 activity로 이동할 때, activiy의 transition 상태들을 처리한다.)


super.onCreate:

When you call super.onCreate it will provide empty graphical window on which you can load your screen. If you comment super.oncreate(); then it will crash your program because there is no container to load your screen.

(super.onCreate를 호출할 때 화면을 로드할 수 있는 빈 그래픽 창을 제공한다. 만약 super.onCreate()에 무언가 작성한다면 super.onCreate에는 당신의 화면을 로드할 container가 없기 때문에 crash가 일어날 것이다.)


Question #03

Is it possible to have an Activity without UI?

(UI가 없는 Activity는 가능한가?)

                              

   

Answer

Generally every activity will have UI (User Interface) screens. But if programmer wants he can omit UI and do some background functionality with an Activity. Note: To do background functionality its better to use service than an activity with out UI. It makes more sense.

(일반적으로 모든 activity는 UI 화면을 가진다. 그러나 만약 프로그래머가 UI 없이 background 기능만을 수행하기 원한다면 가능하다. background 기능을 수행할 때 UI 없는 activity 보다는 service가 더 좋다.)


Question #04

When a new activity comes on top of your activity completely, then what is the life cycle function that gets executed in the old activity?

(새로운 activity가 완전히 상단에 올라올 때 이전 activity의 생명 주기는?)

                              

   

Answer

- onPause() -> then -> onStop()


Question #05

When a dialog is displayed on top of your activity, is your activity in foreground state or visible state?

(최상단 activity에 dialog가 표시될 때 생명 주기는?)

                              

   

Answer

- It calls onPause(). When a dialog comes on top of an exisiting activity, then exisiting activity will move to partially invisible state by calling onPause().

(onPause()이다. 최상단 activity에 dialog가 표시될 때 onPause() 호출에 의해 일부분만 invisible 된다.)


Question #06

What is the mandatory activity life cycle function that will get called in case of configuration changes?

(configuration change인 경우 때 필수로 호출되는 생명 주기는?)

                              

   

Answer

In case of low memory or configuration changes, android will call both onPause() and onSaveInstanceState() with out fail. Exception: there is one exceptional case, that is if programmer is handling configuration changes, then in that case it will not call those functions.

(메모리 부족이나 configuration change인 경우, android는 onPause()와 onSaveInstanceState를 반드시 호출한다. 만약 프로그래머가 configuration change를 직접 처리하는 경우엔 예외적으로 이 함수들을 호출하지 않는다.)


Question #07

Where to register broadcast receivers that updates UI?

(UI를 업데이트하는 broadcast receiver는 어디에 등록해야 하나?)

                              

   

Answer

onStart() function will be called just before your activity will be made visible to the user. So any thing that affects UI has to be registered in onStart() function.

(onStart() 함수는 activity가 유저에게 보이기 바로 직전에 호출되기 때문에 UI에 영향을 주는 것들은 onStart() 함수에 등록한다.)


Question #08

What is the difference between px, dp, dip, and dpi?

(px, dp, dip, dpi?)

                              

   

Answer

px - is meant for absolute pixels. This is used if you want to give in terms of absolute pixels for width or height. Not recommended.

(px는 절대 화소를 의미한다. 너비 또는 높이에 대한 절대 픽셀의 관점에서 부여할 경우에 사용됩니다. 추천하지 않는다.)


dp/ dip - both mean same, density independent pixels. This is alternative of px. Generally we never use px because it is absolute value. If you use px to set width or height, and if that application is being downloaded into different screen sized devices, then that view will not stretch as per the screen original size. dp is highly recommended to use in place of px.

(dp / dip 둘 다 픽셀에 독립적인 밀도라는 의미이다. 픽셀의 대안이다. 일반적으로 픽셀은 절대적인 값이기 때문에 절대 사용하지 않는다. 너비와 높이 지정을 px로 하는 경우, 다른 크기의 화면을 가진 디바이스에 따라 해당 뷰는 신축적이지 않다. dp는 px 대신 사용하길 강력히 추천한다.)


Use dp if you want to mention width and height to grow & shrink dynamically based on screen sizes.

(화면 크기에 따라 동적으로 너비와 높이를 확대/축소하기 원할 경우 DP를 사용합니다.)


if we give dp/dip, android will automatically calculate the pixel size on the basis of 160 pixel sized screen.

(dp/dip로 주면 자동으로 160 픽셀 크기의 화면에 기초하여, 화소 크기를 계산한다.)


sp - Scale independent pixels. when mentioning the font sizes to fit for various screen sizes, use sp. This is similar to dp. Use sp especially for font sizes to grow & shrink dynamically based on screen sizes.

(픽셀에 독립적이다. 다양한 화면 사이즈에 핏 하게 폰트 사이즈를 지정하고 싶으면 sp를 이용해라. dp와 비슷하지만 sp는 폰트를 화면 크기에 따라 동적으로 너비와 높이를 확대/축소해준다.)

* 제 기억에 text를 sp로 하면 setting의 폰트 크기 크게/작게 값이 따라 크기가 조절되지만 dp는 조절이 안 되는 걸로 기억합니다.


dpi- dots per inch. It is the resolution factor.

(dpi는 인치 당 도트 개수입니다. 해상도 요소입니다.)


Math logic behind it:

1dp = 1px in 160 dpi screen. Means 1 dp is equal to 1 physical px of a device having 160 dots per inch. so no of dynamic pixles for a given dp is = (dp's)*(density/160). For example on 240 dpi screen 1dp = 1.5px (physical pixels)


Question #09

What is the life cycle of an activity in case of configuration change or orientation change?

(configuration change이나 orientation change일 때 생명 주기는?)

                              

   

Answer

Configuration change : is either orientation change(phone rotation), or language settings change. In case of configuration change, android will forcefully kill your activity and recreates it, unless you are not handling configuration changes on your own programmatically.

(Configuration change는 폰 회전이나 언어 설정 변경이다. 이 경우 configuration을 프로그래머가 처리하지 않는 경우 강제로 activity를 종료하고 다시 생성한다.)


onPause() -> onSaveInstanceState() -> onStop() -> onDestroy() -> onCreate() -> onStart() -> onRestoreInstanceState() -> onResume()


Question #10

When activity is destroyed, will it be in memory or moved out of it?

(activity가 파괴될 때, 메모리에 남아 있나? 없나?)

                              

   

Answer

Generally after calling onDestroy(), app will be removed from memory. But there is an exception for this rule. If user is visiting an app very frequently then it has to be loaded into memory very frequently. to avoid this over head for the system, android may choose to keep that app in memory even after onDestroy(). This is called "empty process". Process which is killed but still in memory.

(일반적으로 onDestroy()를 호출하면 app은 메모리에서부터 없어진다. 그러나 예외가 있다. 만약 유저가 빈번하게 app을 방문하면 빈번하게 다시 메모리에 로드를 해야 하는데, 이를 방지하기 위해 안드로이드는 onDestoy() 이후에도 메모리를 유지할 수 있다. 이를 "empty process"라고 하고. 프로세스는 죽었지만 메모리에 남아있는 것을 의미한다.)


https://android.googlesource.com/platform/frameworks/base/+/master/services/core/java/com/android/server/am/ProcessList.java#126


기본적으로 activity가 destroy 될 경우, empty process가 되고 가용 메모리에 여유가 있다면 최대 30분까지 남아 있습니다.

// We allow empty processes to stick around for at most 30 minutes.
static final long MAX_EMPTY_TIME = 30*60*1000;

Question #11

What is the life cycle of an activity in case of press a homebutton?

(homebutton 누를 때 생명 주기는?)

                              

   

Answer

- When we press home button any activities, that will be moved to background state (invisible state), so it calls onStop() on that activity.

(어떤 activity에서든 home 버튼을 누를 때 보이지 않는 background 상태로 가기 때문에, onStop()을 호출한다.)


Question #12

When an activity is in stopped state, is it still in memory or not?

(activity가 정지 상태 일 때, 메모리에 남아 있나? 없나?)

                              

   

Answer

- When onStop() is called, then activity is still in memory and all its states and variables are intact.

(onStop()이 호출될 때, activity는 여전히 메모리에 남아 있고 상태와 변수들은 그대로이다.)


Question #13

What is a context in android?

(context?)

                              

   

Answer

It is an interface to global information of an application.

(애플리케이션의 global 정보에 대한 인터페이스이다.)


- Contexts are generally used to create a new components or objects, like views. Contexts are also used to start an activity, or service or a receiver.

(Context는 일반적으로 새로운 component나 view와 같은 객체를 생성할 때 이용한다. Context는 activity, service, receiver를 시작할 때도 쓰인다.)


- There are two types of contexts, activity context(this) and applicationcontext. You can obtain application context by getApplicationContext() method.

(activity context(this)와 applicationContext 두 가지가 있다.)


Question #14

If my application is having one activity - in background state, service - in running state; then what is my process priority?

(background 상태의 activity와 running 상태의 service 중 더 높은 우선순위 프로세스는?)

                              

   

Answer

- service process priority(3)

foreground process(1),  visible process(2), service process priority(3), empty process(5)


Service


Question #01

How to implement binder services, when client applications are in different processes?

(클라이언트 어플리케이션이 다른 프로세스에 있을 때 binder service를 실행시키는 방법은?)

                              

   

Answer

- Binder is used if both client and server are in same application.

(바인더는 클라이언트와 서버가 같은 어플리케이션에 있을 때 이용한다.)


If client and service (server) are in different applications, then this can be implemented in two ways:

(만약 클라이언트와 서비스(서버) 들이 다른 어플리케이션에 있다면, 아래 두 가지 방법으로 구현한다.


1. Messenger - is a simple way to implement binder service, which is single threaded mode. With this, your service can handle only one client request at a time.

(하나의 스레드 모드에서 바인더 서비스를 구현하는 쉬운 방법이다. 이 방법으로는 한 번에 오직 하나의 클라이언트 리퀘스트만 처리할 수 있다.)


2. aidl (Android interface definition language) - use it if you want multi threaded capability for your server/service. With this, your service can handle multiple requests at a time. But little complicated. Make sure that you are writing always thread safe program in your service when using with aidls. This is not recommended for most of the implementations.

(서버/서비스를 위해 여러 개의 스레드를 안정적으로 돌리기 위해서 aidl을 이용한다. 이 방법으로 한 번에 여러 개의 리퀘스트를 처리할 수 있다. 그러나 조금 복잡하다. aidl을 이용할 때는 안정적으로 작성되었는지 반드시 확인해라.)


Question #02

What is the difference between service and intentservice in android?

(service와 intentservice의 차이점은?)

                              

   

Answer

i. Intentservice by default will create one separate thread to handle the service functionality. All the startservice requests for intentservice will be routed to that thread.

(기본적으로 Intentservice는 service 기능을 처리할 수 있는 하나의 별도의 스레드를 생성합니다. intentservice의 모든 startservice 요청은 해당 스레드에 연결됩니다.)


ii. Where as service by default runs in main thread. All the startservice requests will be routed to main thread by default.

(기본적으로 메인 스레드에서 실행되는 서비스는 모든 startservice 요청들을 메인 스레드로 연결됩니다.)


iii. While implementing a service, programmer has to implement onCreate(), onStartCommand(), and onDestroy() methods.

(service를 실행시키기 위해 프로그래머는 onCreate(), onStartCommand(), onDestroy() 메소드를 구현해야 한다.)


iv. Where as while implementing IntentService programmer has to implement only onHandleIntent().

(IntentService를 실행시키기 위해 프로그래머는 오직 onHandleIntent()만 구현하면 된다.)


v. After starting IntentService, it will be automatically closed if there are no pending startService requests.

(IntentService 시작 후, 더 이상의 startService 요청들이 없으면 자동으로 종료된다.)


vi. Where as for normal service programmer has to stop the service explicitly either by using stopSelf() or stopService() methods.

(일반 service 프로그래머는 stopSelf()나 stopService() 메소드를 이용하여 명시적으로 종료해야 한다.)


vii. Don't try to touch UI from IntentService's onHandleIntent() method directly, as that function runs in a separate thread. (Not in main thread).

(IntentService의 onHandleIntent()에서 직접 UI를 건드리지 말고 별도의 스레드를 통하라.)


Question #03

What is the life cycle of a started service?

(started 서비스의 생명 주기는?)

                              

   

Answer

- onCreate() -> onStartCommand() -> onDestroy().

This is the life cycle of a started service. onBind() and onUnbind() will come into picture for only binded services. previously in old versions onStart() was there in place of onStartCommand().

(onBind(), onUnbind()는 binded 서비스에서 쓰인다. 이전 오래된 버전에서는 onStart()가 onStartCommand() 자리에 있었다.)


Question #04

To do some back ground functionality in an activity, which is better? thread or service?

(activity에서 back ground 작업을 수행하기 위해 스레드와 서비스 중 나은 것은?)

                              

   

Answer

- It is better to use services with thread, because threads in activity will have less priority compared to thread in a service in case if that activity is in background or stopped state. more over in case of low memory if it kills thread in activity, there is no way that android will recreate it. all these disadvantages are overcome in services with android. But still if you want to use a thread with activity then as long as programmer make sure that cleaning and creation of thread is done properly, then there won't be any problem.

(서비스를 이용하는 것이 더 좋다, 왜냐면 background 또는 정지 상태의 activity 스레드 보다 서비스가 우선순위가 더 높기 때문이다. 나아가 메모리 부족일 때 activity의 스레드를 죽이게 되면, 다시 재생성할 방법이 없기 때문이다. 이러한 모든 단점은 서비스로 극복된다. 그럼에도 불구하고 스레드를 이용하기 원한다면 스레드가 제대로 삭제, 재생성되는지 제대로 확인해야만 아무런 문제가 없다.)


Question #05

How to move a service to foreground?

(service를 foreground로 옮기는 방법은?)

                              

   

Answer

- call startForeground(int id, Notification notification)


Question #06

What is not true about a binder service?

(바인더 서비스에 대해 옳지 않은 것은?)

                              

   

Answer

- If client and server are in different processes, then there are two ways to implement service.

(만약 클라이언트와 서버가 다른 프로세스에 있다면 서비스를 실행할 두 가지 방법이 있다.)


1. Creating a singled threaded server using Binder and Messenge.

(바인더와 메신저를 이용해 단일 스레드 서버를 만든다.)


2. Creating multi threaded server using aidls.

(aidl을 이용해 멀티 스레드 서버를 만든다.)


Question #07

If I want to create a binder service which supports multi threaded architecture, then which of the below concepts i have to use?

(멀티 스레드 아키텍처를 지원하는 바인더 서비스를 생성하려면, 어떤 개념을 이용해야 하는가?)

                              

   

Answer

- If we want to create a service with multi threads and supports binders then we have to use .aidls and implement the stub.

(. aidl을 이용하여 stub를 실행해야 한다.)

http://aroundck.tistory.com/131


Question #08

Is it possible to have a service without any thread?

(별도의 thread 없이 서비스를 가지는 게 가능한가?)

                              

   

Answer

- Service is a component that performs some operation in the background with out having UI. But it does not mean that it will have separate thread to do it. By default if programmer does not provide any thread for the service, then it runs in Main UI thread. Since it is not good practice to run Activity & Services in single thread, it is suggestible to have separate thread for the service, except in few cases like where a given application is not having any activity in it.

(서비스는 UI 없이 background에서 동작하는 component이다. 그러나 분리된 스레드를 가지고 있다는 의미는 아니다. 기본적으로 프로그래머가 어떠한 스레드도 제공하지 않는다면 메인 UI 스레드에서 동작할 것이다. 하나의 스레드에서 Activity와 Service를 동작한다는 점이 좋지 않기 때문에, 예외적으로 어플리케이션이 activity를 가지지 않는 경우를 제외하면, 서비스를 위한 별도의 스레드를 가지는 것이 좋다.)


Question #09

start a service from activity and close activity, what will happen to that service, will it be alive or dead?

(activity에서 service를 시작하고, activity가 닫힌다면, service는 살아있는 가? 죽었는가?)

                              

   

Answer

- service will be keep running in the background, even if the activity which has created is no more alive. But it can stop itself when the work given to it is done. Or others also can kill that service using stopService(), or android also can kill the service forcefully in case of low memory scenarios.

(서비스는 자신을 생성한 activity가 더 이상 살아있지 않더라도 계속 background에서 실행될 것이다. 그러나 주어진 작업이 완료되면 스스로 정지할 수 있다. stopSerivce()를 이용하거나 메모리 부족으로 인해 android가 강제로 서비스를 죽일 수도 있다.)


* stopSelf(), stopService(), low memory


Question #10

How to update UI from a service that has thread?

(스레드를 가진 서비스에서 UI를 업데이트하는 방법은?)

                              

   

Answer

- Android follows singled threaded UI model, i.e other threads should not touch UI with out taking permission of Main UI thread. If other threads want to touch UI, communicate it to Main thread. Many ways are there to achieve it.

(안드로이드는 메인 UI 스레드를 통해 UI를 터치할 수 있다. 만약 다른 스레드가 UI를 터치하기 위해 메인 스레드를 소통하려면 아래와 같은 방법들이 있다.)


1. RunOnUiThread()

2. Use Handlers to communicate to main thread

3. Use AsyncTask and update ui from onPre or onPost or OnProgress


Question #11

What will happen if you start a service with out any thread, that does heavy functionality?

(만약 별도의 스레드 없이 heavy 한 기능을 가진 서비스를 실행하면 어떤 일이 벌어지는가?)

                              

   

Answer

- Since android gives only one thread per application, default all activities will run in that thread. but service also performs long running operations in the background, it is not suggestible to run service also in same thread which may hang your activities which lead to ANR.

(안드로이드는 어플리케이션 당 하나의 스레드만 제공하기 때문에 기본적으로 모든 작업은 해당 스레드에서 동작한다. 그러나 background에서 오랜 시간이 걸리는 동작을 수행한다면, ANR이 일어날 수 있다.)


* 서비스가 20초 이상 처리하지 못할 때. 


Question #12

What are the various return values of onStartCommand(), and when to use what?

(onStartCommand()의 return 값들은? 언제 쓰이는가?)

                              

   

Answer

- START_STICKY : in case if android stops our service forcefully, then restart service by sending intent null.

(안드로이드가 서비스를 강제 정지한 경우, null intent를 보내서 재시작한다.)


- START_NOT_STICKY : in case if android stops our service forcefully, then don't restart service, until user restarts it.

(안드로이드가 서비스를 강제 정지한 경우, 재시작하지 않는다.)


- START_REDELIVER_INTENT : in case if android stops our service forcefully, then restart service by re-sending the intent.

(안드로이드가 서비스를 강제 정지한 경우, 동일한 intent를 보내서 재시작한다.)


Question #13

What is the difference between startservice and bindservice?

(startservice와 bindservice 차이는?)

                              

   

Answer

http://rosaria1113.tistory.com/238




갑자기 Skillgun 사이트가 안들어가지네요ㅠ

매거진의 이전글 안드로이드 면접 질문 #02
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari