How to finish an Activity from another class?

Asked

Viewed 659 times

0

I need to close an Activity if it has opened, when a certain timer has finished, how do I do it ? because to use Finish I need context.

I tried to cast a cast, but to no avail:

if (dados.getvideorodando()){
  try {
    ((Video2)getApplicationContext()).finish();
  }catch (Exception e){
     Log.e(TAG,"Erro ao fechar actitivy " + e);
  }
}

1 answer

2


You can use a broadcast, which would serve as a system in your Activity.

Whereas you are on an Activity B and are trying to close an Activity A.

Activitya.java

public class ActivityA extends AppCompatActivity {
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Esse método será chamado ao lançar um broadcast
            // pela activity B
            finish();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...

        // Aqui você registra o seu BroadcastReceiver
        // para escutar um broadcast que tenha a ação "meuFiltro".
        // Você pode alterar esse valor para qualquer outro,
        // desde que também altere na sua activity B
        LocalBroadcastManager.getInstance(this)
            .registerReceiver(broadcastReceiver, new IntentFilter("meuFiltro"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Se essa activity for destruída por alguma outra forma,
        // você não vai precisar finalizá-la pela activity B,
        // pois ela já estará destruída
        // Então aqui o BroadcastReceiver é removido
        LocalBroadcastManager.getInstance(this)
            .unregisterReceiver(broadcastReceiver);
    }
}

Activityb.java

public class ActivityB extends AppCompatActivity {
    ...

    private void fechaActivityA() {
        // Aqui você envia um broadcast e qualquer activity
        // que tiver um BroadcastReceiver registrado com
        // essa mesma action "meuFiltro", será chamado o
        // método onReceive() do BroadcastReceiver
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("meuFiltro"));
    }
}
  • I’m not in another Active I’m in a service, and I already have a broadcast running, would be able to reuse, not need to create another?

  • 1

    Yes, when sending the broadcast, you can pass a boolean inside the Intent indicating that it is to close the activity and within the onReceive of BroadcastReceiver you take the Intent, check that boolean and close the activity. I am explaining this way, because I believe you already have enough knowledge on Android. If you think it necessary, I can update the answer with what I just said.

  • It worked, I did that Boolean you said, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.