programing

Android에서 현재 활동을 완료하는 방법

nasanasas 2020. 10. 28. 08:09
반응형

Android에서 현재 활동을 완료하는 방법


Android 애플리케이션이 있습니다. 진행률 표시 줄이있는 로딩 화면을 만들고 있습니다.

onCreate 메서드에 지연을 입력했습니다. 타이머가 끝나면 현재 활동을 끝내고 새로운 활동을 시작하고 싶습니다.

finish()메서드를 호출 할 때 예외가 발생합니다 .

public class LoadingScreen extends Activity{
    private LoadingScreen loadingScreen;
    Intent i = new Intent(this, HomeScreen.class);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);

        CountDownTimer timer = new CountDownTimer(10000, 1000) //10 second Timer
        {
            public void onTick(long l) 
            {

            }

            @Override
            public void onFinish() 
            {
                loadingScreen.finishActivity(0);
                startActivity(i);
            };
        }.start();
    }
}

진행률 표시 줄이 완료되면 종료되도록 코드를 변경하려면 어떻게해야합니까?


로딩 화면을 수행하는 경우 활동 스택에 유지하지 않도록 매개 변수를 설정하기 만하면됩니다. 활동을 정의하는 manifest.xml에서 다음을 수행합니다.

<activity android:name=".LoadingScreen" android:noHistory="true" ... />

그리고 코드에서 더 이상 .finish ()를 호출 할 필요가 없습니다. 그냥 startActivity (i);

현재 활동의 인스턴스를 별도의 필드에 보관할 필요도 없습니다. LoadingScreen.this.doSomething()대신 다음과 같이 언제든지 액세스 할 수 있습니다.private LoadingScreen loadingScreen;


이 예제를 사용해 보았지만 비참하게 실패했습니다. 핸들러 내에서 finish () / finishactivity ()를 호출 할 때마다이 위협적인 결과로 끝납니다 java.lang.IllegalAccess Exception. 질문을 한 사람에게 어떻게 작동했는지 모르겠습니다.

대신 내가 찾은 해결책은 다음과 같은 활동에서 방법을 만드는 것입니다.

void kill_activity()
{ 
    finish();
}

핸들러의 실행 메소드 내부에서이 메소드를 호출하십시오. 이것은 나를위한 매력처럼 작동했습니다. 이것이 "다른 스레드에서 활동을 닫는 방법"으로 어려움을 겪는 사람에게 도움이되기를 바랍니다.


finish()백그라운드 스레드가 아닌 UI 스레드에서 호출해야합니다 . 이를 수행하는 방법은 핸들러를 선언하고 핸들러에게 UI 스레드에서 Runnable을 실행하도록 요청하는 것입니다. 예를 들면 :

public class LoadingScreen extends Activity{
    private LoadingScreen loadingScreen;
    Intent i = new Intent(this, HomeScreen.class);
    Handler handler;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        setContentView(R.layout.loading);

        CountDownTimer timer = new CountDownTimer(10000, 1000) //10seceonds Timer
        {
             @Override
             public void onTick(long l) 
             {

             }

             @Override
             public void onFinish() 
             {
                 handler.post(new Runnable() {
                     public void run() {
                         loadingScreen.finishActivity(0);
                         startActivity(i);
                     }
                 });
             };
        }.start();
    }
}

finish()메소드를 호출하십시오 .

context.finish();

새 활동을 시작하고 현재 활동을 완료하려면 다음을 수행 할 수 있습니다.

API 11 or greater

Intent intent = new Intent(OldActivity.this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

API 10 or lower

Intent intent = new Intent(OldActivity.this, NewActivity.class);
intent.setFlags(IntentCompat.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

I hope this can help somebody =)


You can also use: finishAffinity()

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.


I found many answers but not one is simple... I hope this will help you...

try{
    Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
    startActivity(intent);
} finally {
    finish();
}

so, Very simple logic is here, as we know that in java we write code that has some chances of exception in a try block and handle that exception in catch block but in finally block we write code that has to be executed in any cost (Either the exception comes or not).

참고URL : https://stackoverflow.com/questions/5000787/how-to-finish-current-activity-in-android

반응형