打开第二个Activity时想要关闭第一个Activity直接finish就行,但是如果打开第三个Activity时想要关闭第一个Activity就不是那么方便
其中一种方法就是通过广播来关闭,这里讲的是通过本地广播来关闭
在要关闭的Activity中写一个内部类finishAppReceiver,或者写一个BaseActivity,让项目的所有Activity都继承自这个
public class MainActivity extends AppCompatActivity { LocalBroadcastManager localBroadcastManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); localBroadcastManager = LocalBroadcastManager.getInstance(this); } protected BroadcastReceiver finishAppReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { finish(); } }; @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction("FINISH"); localBroadcastManager.registerReceiver(this.finishAppReceiver, filter); } @Override protected void onDestroy() { super.onDestroy(); localBroadcastManager.unregisterReceiver(this.finishAppReceiver); } }
在需要关闭的时候发送广播
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this); Intent finish = new Intent("FINISH"); localBroadcastManager.sendBroadcast(finish);