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?
– Igor Oliveira
Yes, when sending the broadcast, you can pass a boolean inside the
Intent
indicating that it is to close theactivity
and within theonReceive
ofBroadcastReceiver
you take theIntent
, check that boolean and close theactivity
. 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.– Danilo de Oliveira
It worked, I did that Boolean you said, thank you.
– Igor Oliveira