概述:
基于上一篇博客《Android退出程序(一)——单例模式》的学习,我们知道了如何利用单例和循环遍历的方式来退出我们的应用程序。这篇博客则要从另一个角度来解决问题——广播。即是,接收到一个关闭Activity的广播时,就去关闭当前Activity。
类图展示及说明:
从上面的类图中可以看到这里做了一个处理,而这个处理是学习面向对象的Coder要必须掌握的。这里就是对Activity进行了一个扩展——BaseActivity。如果我们要对每个Activity进行添加内部ExitappReceiver类的话,这样势必增加了代码量,且后期不好维护。所以这里就是把ExitappReceiver封装到了一个基础类中,然后让其他需要实现关闭activity的Activity来继承它就好了。
代码示例:
这里只贴出两个比较关键的代码:
1.接收事件
public class BaseActivity extends Activity {
public static final String TAG = BaseActivity.class.getName();
public static final String BROAD_CAST_MESSAGE = TAG + ".BROAD_CAST_MESSAGE";
private ExitappReceiver mReceiver = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver();
}
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
try {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
} catch (Exception e) {
e.printStackTrace();
}
mReceiver = new ExitappReceiver();
filter.addAction(BROAD_CAST_MESSAGE);
registerReceiver(mReceiver, filter);
}
@Override
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
super.onDestroy();
}
class ExitappReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BROAD_CAST_MESSAGE)) {
finish();
}
}
}
}
2.触发事件:
public class TwoActivity extends BaseActivity {
private int getLayoutResID() {
return R.layout.activity_two;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResID());
Button nextButton = (Button) findViewById(R.id.activity_two_button);
nextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendBroadcast();
}
});
}
private void sendBroadcast() {
Intent intent = new Intent();
intent.setAction(BaseActivity.BROAD_CAST_MESSAGE);
sendBroadcast(intent);
}
}