Programing

onStart ()와 onResume ()의 차이점

crosscheck 2020. 5. 28. 07:59
반응형

onStart ()와 onResume ()의 차이점


onStart()전환 상태 의 의미를 얻을 수 없습니다 . onResume()메소드는 항상 이후에 호출 onStart()됩니다. onResume()이후에 호출 된 메소드 onRestart()onCreate()메소드를 제외 하는 이유는 무엇 onStart()입니까? 그 목적은 무엇입니까?

없이는 왜 살 수 없습니까 onStart()? 나는 여전히 그것을 중복으로 간주합니다 (아마도 그 의미를 완전히 이해하지 못하기 때문에).


왜 onStart ()를 제외하고 onRestart () 및 onCreate () 메소드 후에 onResume ()을 호출 할 수 없습니까? 그 목적은 무엇입니까?

첫 번째 대답이 꽤 길었으므로 더 이상 확장하지 않으므로 시도해 보겠습니다.

public DriveToWorkActivity extends Activity
    implements onReachedGroceryStoreListener {
}

public GroceryStoreActivity extends Activity {}

참고 사항 : 나는 의도적으로 super.onCreate(...)등을 호출하지 않았습니다 . 이것은 의사 코드이므로 여기에 예술 라이센스를 부여하십시오. ;)

DriveToWorkActivity따르기 위한 방법 ...

protected void onCreate(...) {
    openGarageDoor();
    unlockCarAndGetIn();
    closeCarDoorAndPutOnSeatBelt();
    putKeyInIgnition();
}

protected void onStart() {
    startEngine();
    changeRadioStation();
    switchOnLightsIfNeeded();
    switchOnWipersIfNeeded();
}

protected void onResume() {
    applyFootbrake();
    releaseHandbrake();
    putCarInGear();
    drive();
}

protected void onPause() {
    putCarInNeutral();
    applyHandbrake();
}

protected void onStop() {
    switchEveryThingOff();
    turnOffEngine();
    removeSeatBeltAndGetOutOfCar();
    lockCar();
}

protected void onDestroy() {
    enterOfficeBuilding();
}

protected void onReachedGroceryStore(...) {
    Intent i = new Intent(ACTION_GET_GROCERIES, ...,  this, GroceryStoreActivity.class);
}

protected void onRestart() {
    unlockCarAndGetIn();
    closeDoorAndPutOnSeatBelt();
    putKeyInIgnition();
}

자, 그것은 또 다른 긴 것입니다 (죄송합니다). 그러나 여기 내 설명이 있습니다 ...

onResume()내가 운전을 시작할 때이고 onPause()일시적으로 멈출 때입니다. 그래서 나는 운전을하다가 빨간불에 도달하여 잠깐 멈춘다. 또 다른 빨간불과 나는 잠시 멈췄다가 초록색으로 다시 시작합니다. onPause() -> onResume() -> onPause() -> onResume()루프는 꽉 하나이며 나의 여행을 통해 여러 번 발생합니다.

재시작을 통해 다시 멈춰서 (나의 여행을 준비하기 위해) 다시 시작하는 루프는 덜 일반적입니다. 어떤 경우에는, 나는 식료품 점을 발견하고 GroceryStoreActivity가 시작됩니다 (내 DriveToWorkActivity지점으로 강제 onStop()). 내가 가게에서 돌아 오면, 나는 통과 onRestart()하고 onStart()다음 내 여행을 다시 시작합니다.

나는에있어 코드를 넣을 수있는 onStart()양에 onCreate()onRestart()및 대체 할 귀찮게하지 onStart()요구 사이에 수행 할 수있는보다 전혀하지만 onCreate() -> onResume()하고 onRestart() -> onResume(), 더 내가 복제있어 일을.

다시 한 번 인용하면 ...

왜 onStart ()를 제외하고 onRestart () 및 onCreate () 메소드 후에 onResume ()을 호출 할 수 없습니까?

재정의하지 않으면 onStart()이것이 실제로 발생합니다. onStart()메소드는 Activity암시 적으로 호출 되지만 코드의 효과는 실제로 onCreate() -> onResume()또는 onRestart() -> onResume()입니다.


짧은 답변:

활동이 사용자에게 "보이게"되는 상태이기 때문에 onStart 없이는 살 수 없지만, 사용자가 활동과 "상호 작용"할 수는 없지만 다른 작은 대화 상자와 겹칠 수 있습니다. 사용자와 상호 작용하는이 기능은 onStart와 onResume을 차별화하는 기능입니다. 유리문 뒤에있는 사람으로 생각하십시오. 상대방을 볼 수는 있지만 대화 할 수는 없습니다. OnResume은 도어 오프너와 유사하며 상호 작용을 시작할 수 있습니다.

또한 onRestart ()가 가장 적게 이해됩니다. onRestart () 대신 onStop () 후에 onStart () 또는 onResume ()으로 직접 이동하지 않는 이유에 대한 질문을 할 수 있습니다. 작성 부분을 생략하면 onRestart ()가 onCreate ()와 부분적으로 동일하다는 것을 이해하면 이해하기 쉬워집니다. 기본적으로 두 상태 모두 onStart ()로 이어집니다 (즉, 활동이 표시됨). 따라서 두 상태 모두 표시 할 항목을 "준비"해야합니다. OnCreate는 표시 할 항목을 "생성"해야 할 추가 책임이 있습니다.

그래서 그들의 코드 구조는 다음과 같이 맞을 수 있습니다 :

onCreate()
{
     createNecessaryObjects();

     prepareObjectsForDisplay();
}


onRestart()
{
     prepareObjectsForDisplay();

}

Google이 다음과 같은 것이 아닌 직관적이지 않은 이름을 선택했기 때문에 전체 혼란이 발생합니다.

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 

활동 다이어그램은 다음과 같이 해석 될 수 있습니다.

Android Activity Lifecycle


onStart() called when the activity is becoming visible to the user. onResume() called when the activity will start interacting with the user. You may want to do different things in this cases.

See this link for reference.


onResume() is called:

  1. after onStart()
  2. when the Activity comes to the foreground.

From http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle: alt text


The book "Hello, Android, Introducing Google's Mobile Development Platform" gives a nice explanation of the life cycle of android apps. Luckily they have the particular chapter online as an excerpt. See the graphic on page 39 in http://media.pragprog.com/titles/eband3/concepts.pdf

By the way, this book is highly recommendable for android beginners!


A particularly feisty example is when you decide to show a managed Dialog from an Activity using showDialog(). If the user rotates the screen while the dialog is still open (we call this a "configuration change"), then the main Activity will go through all the ending lifecycle calls up untill onDestroy(), will be recreated, and go back up through the lifecycles. What you might not expect however, is that onCreateDialog() and onPrepareDialog() (the methods that are called when you do showDialog() and now again automatically to recreate the dialog - automatically since it is a managed dialog) are called between onStart() and onResume(). The pointe here is that the dialog does not cover the full screen and therefore leaves part of the main activity visible. It's a detail but it does matter!


onStart()

  1. Called after onCreate(Bundle) or after onRestart() followed by onResume().
  2. you can register a BroadcastReceiver in onStart() to monitor changes that impact your UI, You have to unregister it in 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.

onResume()

  1. Called after onRestoreInstanceState(Bundle), onRestart(), or onPause()
  2. Begin animations, open exclusive-access devices (such as the camera)

onStart() normally dispatch work to a background thread, whose return values are:

  • START_STICKY to automatically restart if killed, to keep it active.

  • START_REDELIVER_INTENT for auto restart and retry if the service was killed before stopSelf().

onResume() is called by the OS after the device goes to sleep or after an Alert or other partial-screen child activity leaves a portion of the previous window visible so a method is need to re-initialize fields (within a try structure with a catch of exceptions). Such a situation does not cause onStop() to be invoked when the child closes.

onResume() is called without onStart() when the activity resumes from the background

For More details you can visits Android_activity_lifecycle_gotcha And Activity Lifecycle


onStart() means Activity entered into visible state and layout is created but can't interact with this activity layout.

Resume() means now you can do interaction with activity layout.


Hopefully a simple explanation : -

onStart() -> called when the activity becomes visible, but might not be in the foreground (e.g. an AlertFragment is on top or any other possible use case).

onResume() -> called when the activity is in the foreground, or the user can interact with the Activity.


Note that there are things that happen between the calls to onStart() and onResume(). Namely, onNewIntent(), which I've painfully found out.

If you are using the SINGLE_TOP flag, and you send some data to your activity, using intent extras, you will be able to access it only in onNewIntent(), which is called after onStart() and before onResume(). So usually, you will take the new (maybe only modified) data from the extras and set it to some class members, or use setIntent() to set the new intent as the original activity intent and process the data in onResume().


Reference to http://developer.android.com/training/basics/activity-lifecycle/starting.html

onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it. Always followed by onPause().

onPause() Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns. Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

참고URL : https://stackoverflow.com/questions/4553605/difference-between-onstart-and-onresume

반응형