developer tip

다른 활동에서 활동 완료

optionbox 2020. 8. 31. 07:42
반응형

다른 활동에서 활동 완료


다음과 같이 다른 활동에서 한 활동을 완료하고 싶습니다.

활동 [A]에서 버튼을 클릭하면 활동 [A]를 끝내지 않고 활동 [B]를 호출합니다.

이제 활동 [B]에는 새로 만들기수정 두 개의 버튼이 있습니다 . 사용자가 수정을 클릭하면 모든 옵션이 선택된 상태로 스택에서 활동 [A]를 팝합니다.

하지만 사용자 가 Activity [B]에서 New 버튼을 클릭 하면 스택에서 Activity [A]를 완료하고 해당 Activity [A]를 스택에 다시로드해야합니다.

시도하고 있지만 스택에서 활동 [A]를 완료 할 수 없습니다. 어떻게해야합니까?

코드를 다음과 같이 사용하고 있습니다.

활동 [A]에서 :

Intent GotoB = new Intent(A.this,B.class);
startActivityForResult(GotoB,1);

같은 활동의 다른 방법

public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (requestCode == 1)
    {
        if (resultCode == 1) {
            Intent i = getIntent();
            overridePendingTransition(0, 0);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            finish();

            overridePendingTransition(0, 0);
            startActivity(i);
        }
    }
}

그리고 활동 [B]에서 버튼 클릭 :

setResult(1);
finish();

  1. 매니페스트 파일에서 활동 A를 만듭니다. launchMode = "singleInstance"

  2. 사용자가 new를 클릭 FirstActivity.fa.finish();하면 새로운 Intent를 실행하고 호출합니다.

  3. 사용자가 수정을 클릭하면 새 인 텐트를 호출하거나 단순히 활동 B를 완료합니다.

첫 번째 방법

첫 번째 활동에서 다음 Activity object과 같이 선언 하십시오.

public static Activity fa;
onCreate()
{
    fa = this;
}

이제 다른 개체 Activity에서이 개체를 사용하여 이와 같은 첫 번째 활동을 완료합니다.

onCreate()
{
    FirstActivity.fa.finish();
}

두 번째 방법

FirstActivity이동하자마자 끝내고 싶은 액티비티 를 호출하면서 호출하면서 플래그를 추가 할 수 있습니다.FirstActivity

intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

그러나이 플래그를 사용하면 원하지 않는 경우에도 활동이 완료됩니다. 그리고 언젠가 onBack당신이 보여주고 싶다면 FirstActivity의도를 사용하여 호출해야 할 것입니다.


할 수 있지만 정상적인 활동 흐름을 깨서는 안된다고 생각합니다. 활동을 마치고 싶다면 활동 B에서 활동 A로 브로드 캐스트를 보낼 수 있습니다.

Create a broadcast receiver before starting your activity B:

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (action.equals("finish_activity")) {
            finish();
            // DO WHATEVER YOU WANT.
        }
    }
};
registerReceiver(broadcastReceiver, new IntentFilter("finish_activity"));

Send broadcast from activity B to activity A when you want to finish activity A from B

Intent intent = new Intent("finish_activity");
sendBroadcast(intent);

I hope it will work for you...


This is a fairly standard communication question. One approach would be to use a ResultReceiver in Activity A:

Intent GotoB=new Intent(A.this,B.class);
GotoB.putExtra("finisher", new ResultReceiver(null) {
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        A.this.finish();
    }
});
startActivityForResult(GotoB,1);

and then in Activity B you can just finish it on demand like so:

((ResultReceiver)getIntent().getExtra("finisher")).send(1, new Bundle());

Try something like that.


There is one approach that you can use in your case.

Step1: Start Activity B from Activity A

startActivity(new Intent(A.this, B.class));

Step2: If the user clicks on modify button start Activity A using the FLAG_ACTIVITY_CLEAR_TOP.Also, pass the flag in extra.

Intent i = new Intent(B.this, A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("flag", "modify");
startActivity(i);
finish();

Step3: If the user clicks on Add button start Activity A using the FLAG_ACTIVITY_CLEAR_TOP.Also, pass the flag in extra. FLAG_ACTIVITY_CLEAR_TOP will clear all the opened activities up to the target and restart if no launch mode is defined in the target activity

Intent i = new Intent(B.this, A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("flag", "add");
startActivity(i);
finish();

Step4: Now onCreate() method of the Activity A, need to retrieve that flag.

String flag = getIntent().getStringExtra("flag");
if(flag.equals("add")) {
    //Write a code for add
}else {
    //Write a code for modifying
}

See my answer to Stack Overflow question Finish All previous activities.

What you need is to add the Intent.FLAG_CLEAR_TOP. This flag makes sure that all activities above the targeted activity in the stack are finished and that one is shown.

Another thing that you need is the SINGLE_TOP flag. With this one you prevent Android from creating a new activity if there is one already created in the stack.

Just be wary that if the activity was already created, the intent with these flags will be delivered in the method called onNewIntent(intent) (you need to overload it to handle it) in the target activity.

Then in onNewIntent you have a method called restart or something that will call finish() and launch a new intent toward itself, or have a repopulate() method that will set the new data. I prefer the second approach, it is less expensive and you can always extract the onCreate logic into a separate method that you can call for populate.


I've just applied Nepster's solution and works like a charm. There is a minor modification to run it from a Fragment.

To your Fragment

// sending intent to onNewIntent() of MainActivity
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("transparent_nav_changed", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

And to your OnNewIntent() of the Activity you would like to restart.

// recreate activity when transparent_nav was just changed
if (getIntent().getBooleanExtra("transparent_nav_changed", false)) {
    finish(); // finish and create a new Instance
    Intent restarter = new Intent(MainActivity.this, MainActivity.class);
    startActivity(restarter);
}

Start your activity with request code :

StartActivityForResult(intent,1003);

And you can close it from any other activity like this :

FinishActivity(1003);

I think i have the easiest approach... on pressing new in B..

Intent intent = new Intent(B.this, A.class);
intent.putExtra("NewClicked", true);
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

and in A get it

  if (getIntent().getBooleanExtra("NewClicked", false)) {
        finish();// finish yourself and make a create a new Instance of yours.
      Intent intent = new Intent(A.this,A.class);
      startActivity(intent);
    }

I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me

I overrode onPause and called finish() inside that method.


First call startactivity() then use finish()

참고URL : https://stackoverflow.com/questions/10379134/finish-an-activity-from-another-activity

반응형