Development Tip

Android에서 애플리케이션을 닫고 홈 화면을 시작합니다.

yourdevel 2020. 10. 17. 12:31
반응형

Android에서 애플리케이션을 닫고 홈 화면을 시작합니다.


두 가지 활동이 있습니다. 첫 번째는 두 번째를 시작합니다. 두 번째 활동에서는 System.exit(0)애플리케이션을 강제 종료하기 위해 호출 하지만 애플리케이션이 홈 화면으로 돌아가는 대신 첫 번째 활동이 자동으로 표시됩니다. 이를 방지하고 애플리케이션이 홈 화면으로 돌아가도록하려면 어떻게해야합니까?


응용 프로그램을 종료하지 않는 것에 대해 정말로 생각해야합니다. 이것은 Android 앱이 일반적으로 작동하는 방식이 아닙니다.


짧은 대답 : 대신을 (를) 호출 moveTaskToBack(true)하십시오ActivitySystem.exit() . 사용자가 다시 사용하기를 원할 때까지 애플리케이션을 숨 깁니다.

더 긴 대답은 또 다른 질문으로 시작합니다. 애플리케이션을 왜 죽이고 싶습니까?

Android OS는 메모리 관리 및 프로세스 등을 처리하므로 Android에서이 문제에 대해 걱정할 수 있습니다. 사용자가 애플리케이션에서 나가고 자하는 경우 홈 버튼을 누르면 애플리케이션이 효과적으로 사라집니다. 나중에 전화에 더 많은 메모리가 필요하면 OS가 응용 프로그램을 종료합니다.

만큼 당신이있어로서 적절 라이프 사이클 이벤트에 응답 응용 프로그램이 계속 실행되지 않았거나, 당신도 사용자의 요구도 상관합니다.

따라서 애플리케이션 호출을 숨기고 moveTaskToBack()Android가 종료 시점을 결정하도록하려면.


이를 달성하는 가장 쉬운 방법은 아래에 나와 있습니다 (Android의 기본 메모리 관리에 영향을주지 않습니다. 프로세스 종료가 포함되지 않음).

  1. 이 인 텐트를 사용하여 활동 시작 :

    Intent intent = new Intent(this, FinActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    
  2. 대상 활동 FinActivity.class에서에서 finish ()를 호출 onCreate합니다.

설명 된 단계 :

  1. 다른 모든 활동을 지우고 (FLAG_ACTIVITY_CLEAR_TOP)현재 활동 을 삭제하는 인 텐트를 만듭니다 .

  2. 활동 자체가 파괴됩니다. 대안은 finActivity에서 스플래시 화면을 만들 수 있다는 것입니다. 이것은 선택 사항입니다.


Android에는 설명서에 따라 애플리케이션을 안전하게 닫을 수있는 메커니즘이 있습니다. 종료 된 마지막 활동 (일반적으로 애플리케이션이 시작될 때 처음 나타난 주요 활동)에서 onDestroy () 메서드에 몇 줄만 배치하면됩니다. System.runFinalizersOnExit (true)를 호출 하면 응용 프로그램이 종료 될 때 모든 개체가 종료되고 가비지 수집됩니다. 예를 들면 :

public void onDestroy() {
    super.onDestroy();

    /*
     * Notify the system to finalize and collect all objects of the
     * application on exit so that the process running the application can
     * be killed by the system without causing issues. NOTE: If this is set
     * to true then the process will not be killed until all of its threads
     * have closed.
     */
    System.runFinalizersOnExit(true);

    /*
     * Force the system to close the application down completely instead of
     * retaining it in the background. The process that runs the application
     * will be killed. The application will be completely created as a new
     * application in a new process if the user starts the application
     * again.
     */
    System.exit(0);
}

마지막으로 Android는 애플리케이션에 HOME 키 이벤트를 알리지 않으므로 HOME 키를 눌러도 애플리케이션을 닫을 수 없습니다 . Android 는 개발자가 사용자가 애플리케이션을 떠나는 것을 막을 수 없도록 키 이벤트를 자체적으로 예약합니다 .


첫 번째 활동의 태그에 noHistory = "true"를 지정 하거나 두 번째 활동을 시작하자마자 첫 번째 활동을 완료 할 수도 있습니다 (David가 말했듯이).

AFAIK, "강제 종료"는 애플리케이션이 실행되는 JVM을 호스팅하는 프로세스를 종료하고 System.exit ()는 애플리케이션 인스턴스를 실행하는 JVM을 종료합니다. 둘 다 갑작스러운 종료의 형태이며 정상적인 응용 프로그램 흐름에는 권장되지 않습니다.

프로그램이 수행 할 수있는 논리 흐름을 다루기 위해 예외를 포착하는 것과 마찬가지로 권장되지 않습니다.


이 방법을 사용하여 활동을 닫습니다!

public static void closeAllBelowActivities(Activity current) {
    boolean flag = true;
    Activity below = current.getParent();
    if (below == null)
        return;
    System.out.println("Below Parent: " + below.getClass());
    while (flag) {
        Activity temp = below;
        try {
            below = temp.getParent();
            temp.finish();
        } catch (Exception e) {
            flag = false;
        }
    }
}

두 번째 활동을 시작하면 finish()번째 활동이 즉시 :

startActivity(new Intent(...));
finish();

android.os.Process.killProcess(android.os.Process.myPid()); 잘 작동하지만 Android 플랫폼이 메모리 관리에 대해 걱정하도록하는 것이 좋습니다.


System.exit () 할 수 없습니다. 안전하지 않습니다.

다음 중 하나를 수행 할 수 있습니다. Process.killProcess (Process.myPid ());


나는 이것을 사용한다 :

1) 상위 활동은 "startActivityForResult"메소드로 보조 활동을 호출합니다.

2) 마감일 때 보조 활동에서 :

int exitCode = 1; // Select the number you want
setResult(exitCode);
finish();

3) 그리고 상위 활동에서 "onActivityResult"메소드를 재정의합니다.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    int exitCode = 1;
    if(resultCode == exitCode) {
        super.setResult(exitCode); // use this if you have more than 2 activities
        finish();
    }
}

이것은 나를 위해 잘 작동합니다.


finish방법을 사용하십시오 . 더 간단하고 쉬운 방법입니다.

this.finish();

영구 소켓 연결을 사용하는 응용 프로그램으로 작업 할 때이 finish()메서드는 연결을 해제하지 않습니다. 정상적인 상황에서는를 사용 finish()하는 것이 가장 좋지만 앱을 종료하고 사용중인 모든 리소스를 해제해야하는 경우 killProcess. 나는 그것을 사용하는 데 아무런 문제가 없었습니다.


startActivityForResult로 두 번째 활동을 시작하고 두 번째 활동에서 첫 번째 활동의 onActivityResult 메서드에서 기본 애플리케이션을 닫는 값을 반환합니다. 이것이 Android가 올바른 방식이라고 생각합니다.


다음을 시도하십시오. 그것은 나를 위해 작동합니다.

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); 
ComponentName componentInfo = taskInfo.get(0).topActivity;
am.restartPackage(componentInfo.getPackageName());

A> B> C> D> E와 같은 활동 스택이 있다고 가정합니다. 활동 D에 있으며 앱을 닫으려고합니다. 이것이 당신이 할 일입니다-

종료하려는 활동에서 (활동 D)-

Intent intent = new Intent(D.this,A.class);
intent.putExtra("exit", "exit");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

RootActivity에서 (즉, 기본 활동, 여기서 활동 A)-

@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.hasExtra("exit")) {
            setIntent(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getIntent() != null) {
            if (("exit").equalsIgnoreCase(getIntent().getStringExtra(("exit")))) {
                onBackPressed();
            }
        }
    }

onNewIntent는 활동이 살아 있으면이를 시작한 첫 번째 인 텐트를 가져 오기 때문에 사용됩니다. 새로운 것이 아닙니다. 자세한 내용- 문서


실제로 조용합니다.

이 작업을 수행하는 방법은 모두가 사용할 수있는 정적 변수에 플래그를 저장하는 것입니다. 그런 다음 종료 할 때이 플래그를 설정하고 모든 활동이이 플래그를 확인합니다 onResume. 플래그가 설정되면 System.exit해당 활동에 대해 발행합니다 .

이렇게하면 모든 활동이 플래그를 확인하고 플래그가 설정되면 정상적으로 닫힙니다.


You are wrong. There is one way to kill an application. In a class with super class Application, we use some field, for example, killApp. When we start the splash screen (first activity) in onResume(), we set a parameter for false for field killApp. In every activity which we have when onResume() is called in the end, we call something like that:

if(AppClass.killApp())
    finish();

Every activity which is getting to the screen have to call onResume(). When it is called, we have to check if our field killApp is true. If it is true, current activities call finish(). To invoke the full action, we use the next construction. For example, in the action for a button:

AppClass.setkillApplication(true);
   finish();
   return;

This is what I did to close the application: In my application I have a base activity class, I added a static flag called "applicationShutDown". When I need to close the application I set it to true.

In the base activity onCreate and onResume after calling the super calls I test this flag. If the "applicationShutDown" is true I call finish on the current Activity.

This worked for me:

protected void onResume() {
    super.onResume();
    if(BaseActivity.shutDownApp)
    {
        finish();
        return;

    }}

Run the second activity using start activity for result:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);

//This line is important
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

startActivityForResult(intent, REQUEST_CODE);

Add this function to the first Activity:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(rquestCode == REQUEST_CODE)
        if(resultCode == RESULT_CANCELED)
            finish();
}

And add this to the second Activity:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

        Log.i(TAG, "Back key pressed");
        setResult(RESULT_CANCELED);
        finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

It is not recommended, but you can still use this. Better go with this solution in case you need to quit the app.

According to me, the best solution is to finish every activity in your app like below.

Step 1. Maintain a static variable in mainactivity. Say,

public static boolean isQuit = false;

Step 2. On click event of an button, set this variable to true.

mainactivity.isQuit = true;
finish();

Step 3. And in every activity of your application, have the onrestart method as below.

@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    super.onRestart();
    if(mainactivity.isQuit)
        finish();
}

I solved a similar problem: MainActivity starts BrowserActivity, and I need to close the app, when user press Back in BrowserActivity - not to return in MainActivity. So, in MainActivity:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "sm500_Rmt.MainActivity";
    private boolean m_IsBrowserStarted = false;

and then, in OnResume:

    @Override
protected void onResume() {
    super.onResume();
    if(m_IsBrowserStarted) {
        Log.w(TAG, "onResume, but it's return from browser, just exit!");
        finish();
        return;
    }
    Log.w(TAG, "onResume");

... then continue OnResume. And, when start BrowserActivity:

    Intent intent = new Intent(this, BrowserActivity.class);
    intent.putExtra(getString(R.string.IPAddr), ip);
    startActivity(intent);
    m_IsBrowserStarted = true;

And it looks like it works good! :-)

참고URL : https://stackoverflow.com/questions/2042222/close-application-and-launch-home-screen-on-android

반응형