Nice programing

프로그래밍 방식으로 Android 앱을 종료하는 방법은 무엇입니까?

nicepro 2020. 11. 12. 20:13
반응형

프로그래밍 방식으로 Android 앱을 종료하는 방법은 무엇입니까?


나는 몇 번 읽었 기 때문에이 질문이 여러 번 요청되었다고 확신합니다. 내 고객은 사용자가 클릭하고 종료 할 수있는 버튼을 앱에 삽입하기를 원합니다. 나는 이것을 읽고 부름 finish()이 그것을 할 것이라는 것을 발견 했습니다. 하지만 마무리는 현재 실행중인 활동 만 닫는 것입니까? 활동이 많기 때문에이 경우에는 모든 활동의 인스턴스를 전달하고 완료하거나 모든 활동을 Singleton 패턴으로 만들어야합니다.

또한 Activity.moveTaskToBack(true)홈 화면으로 이동할 수 있다는 것도 알게되었습니다 . 좋아, 이것은 닫히지 않고 프로세스를 배경 화합니다. 그래서 이것이 효과적입니까?

앱을 완전히 닫으려면 어떤 방법을 사용해야합니까? 위에 설명 된 방법 또는 위 방법의 다른 방법 / 기타 사용법이 있습니까?


실제로 모든 사람들은 활동이있을 수있는 onclick 이벤트에서 응용 프로그램을 종료하려고합니다 ....

그래서 친구들은이 코드를 시도합니다. 이 코드를 onclick 이벤트에 넣으십시오.

Intent homeIntent = new Intent(Intent.ACTION_MAIN);
    homeIntent.addCategory( Intent.CATEGORY_HOME );
    homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
    startActivity(homeIntent); 

System.exit (); 호출 할 수 있습니다. 모든 활동에서 벗어나기 위해.

    submit=(Button)findViewById(R.id.submit);

            submit.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
android.os.Process.killProcess(android.os.Process.myPid());
                    System.exit(1);

                }
            });

애플리케이션을 종료하려면 버튼 누름 이벤트 내에서 다음 코드를 사용하세요.

public void onBackPressed() {
  moveTaskToBack(true);
  android.os.Process.killProcess(android.os.Process.myPid());
  System.exit(1);
}

 @Override
    public void onBackPressed() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle("Exit Application?");
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                moveTaskToBack(true);
                                android.os.Process.killProcess(android.os.Process.myPid());
                                System.exit(1);
                            }
                        })

                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

API 16 이후로 이름과 javadoc 설명으로 모든 관련 활동을 닫는 것과 매우 유사한 finishAffinity 메소드를 사용할 수 있습니다.

this.finishAffinity();

이 활동과 동일한 선호도를 가진 현재 작업에서 바로 아래에있는 모든 활동을 완료합니다. 일반적으로 애플리케이션이 다른 작업 (예 : 이해하는 콘텐츠 유형의 ACTION_VIEW에서)으로 시작될 수 있고 사용자가 위쪽 탐색을 사용하여 현재 작업에서 벗어나 자신의 작업으로 전환 한 경우에 사용됩니다. 이 경우 사용자가 두 번째 응용 프로그램의 다른 활동으로 이동 한 경우 작업 전환의 일부로 원래 작업에서 모든 작업을 제거해야합니다.

이 완료는 이전 활동에 결과를 전달할 수 없으며 그렇게하려고하면 예외가 발생합니다.


API 21 부터 매우 유사한 명령을 사용할 수 있습니다.

finishAndRemoveTask();

이 작업의 모든 활동을 완료하고 최근 작업 목록에서 제거합니다.

대안 :

getActivity().finish();
System.exit(0);


int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);


Process.sendSignal(Process.myPid(), Process.SIGNAL_KILL);


Intent i = new Intent(context, LoginActivity.class);
i.putExtra(EXTRA_EXIT, true);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(i);

출처 : 프로그래밍 방식으로 Android 애플리케이션을 종료하는 방법


도움이 되었기를 바랍니다. 행운을 빕니다!


너무 쉽습니다. 사용하다System.exit(0);


정확히 두 가지 가능한 상황이 있습니다.

  1. 활동을 종료 할 수 있습니다.
  2. 또는 응용 프로그램을 종료하려는 경우

다음 코드를 사용하여 활동을 종료 할 수 있습니다.

var intent = new Intent(Intent.ActionMain);
intent.AddCategory(Intent.CategoryHome);
intent.SetFlags(ActivityFlags.NewTask);
startActivity(intent);
finish();

그러나 이것은 동일한 응용 프로그램의 기본 활동을 종료하지 않습니다. 이것은 응용 프로그램을 최소화합니다.

응용 프로그램을 종료하려면 다음 코드를 사용하여 프로세스를 종료하십시오.

android.os.Process.killProcess(android.os.Process.myPid()); 

모노 개발을 위해 그냥 사용

process.KillProcess(Process.MyPid());

어때 this.finishAffinity()

문서에서

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch. Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.


android.os.Process.killProcess(android.os.Process.myPid());

 @Override
    public void onBackPressed() {
        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.addCategory( Intent.CATEGORY_HOME );
        homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(homeIntent);
    }

Use this.finishAffinity(); on that button instead of finish(); If it does not work then you can also try by adding android:noHistory="true" in your manifest and then finish your activity by uisng finish(); or finishAffinity();

Hope it helps....:)


put this one into your onClic:

moveTaskToBack(true);
    finish()

Try this on a call. I sometimes use it in onClick of a button.

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

It instead of closing your app , opens the dashboard so kind of looks like your app is closed.

read this question for more clearity android - exit application code


this will clear Task(stack of activities) and begin new Task

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(1);

Achieving in Xamarin.Android:

    public override void OnBackPressed()
    {
        MoveTaskToBack(true);
        Process.KillProcess(Process.MyPid());
        Environment.Exit(1);
    }

ghost activity called with singletop and finish() on onCreate should do the trick


It works using only moveTaskToBack(true);


If someone still wonders, for Xamarin.Android (in my case also Monogame running on it) the command FinishAndRemoveTask() on Activity does the job very well!


just use the code in your backpress

                    Intent startMain = new Intent(Intent.ACTION_MAIN);
                    startMain.addCategory(Intent.CATEGORY_HOME);
                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(startMain);

If you are using EventBus (or really any other pub/sub library) in your application to communicate between activities you can send them an explicit event:

final public class KillItWithFireEvent
{
    public KillItWithFireEvent() {}

    public static void send()
    {
        EventBus.getDefault().post(new KillItWithFireEvent());
    }
}

The only downside of this is you need all activities to listen to this event to call their own finish(). For this you can easily create shim activity classes through inheritance which just listen to this event and let subclasses implement everything else, then make sure all your activities inherit from this extra layer. The kill listeners could even add some extra functionality through overrides, like avoiding death on certain particular situations.


Instead of System.exit(1) Just use System.exit(0)


Just run the below two lines when you want to exit from the application

android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);

in the fragment

getActivity().finishAndRemoveTask();

in the Activity

finishAndRemoveTask();


Just call these two Function

 finish();
 moveTaskToBack(true);

If you use both finish and exit your app will close complitely

finish();

System.exit(0);


finish();
 finishAffinity();
 System.exit(0);

worked for me

참고URL : https://stackoverflow.com/questions/17719634/how-to-exit-an-android-app-programmatically

반응형