之前学习到多个activity退出总是很麻烦,其实通过网上看到一个思想比较好的退出方式是创建一个Activity的基类,其他的Acticity都继承这个基类.退出使用广播,在需要退出的地方发送一个广播.在基类中接收这个广播.然后finish(),这样就可以了.不用每个Activity都去写代码.创建基类的好处还有很多.基类+广播可以做很多事情。直接上代码了:
基类BaseActivity:
public class BaseActivity extends Activity {
public Activity aty;
public ExitAllBroadCast exitAllBroadCast;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
aty = BaseActivity.this;
exitAllBroadCast = new ExitAllBroadCast();
}
/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
IntentFilter filter = new IntentFilter();// 创建IntentFilter对象
filter.addAction("com.kg.exit.broadcast");
registerReceiver(exitAllBroadCast, filter);// 注册Broadcast Receiver
super.onStart();
}
class ExitAllBroadCast extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
aty.finish();
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(exitAllBroadCast);
}
}
子类Activity01
public class Activity01 extends BaseActivity {
private TextView tx;
private Button btn;
private Context ctx;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ctx = this;
tx = (TextView) findViewById(R.id.tx);
tx.setText("activity01");
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(ctx, Activity02.class);
startActivity(intent);
}
});
}
}
子类
Activity02:
public class Activity02 extends BaseActivity {
public static final int MENU_EXITAPPLICATION = Menu.FIRST;
private TextView tx;
private Button btn;
private Context ctx;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ctx = this;
tx = (TextView) findViewById(R.id.tx);
tx.setText("activity02");
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(ctx, Activity01.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_EXITAPPLICATION, 0,"退出程序");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == MENU_EXITAPPLICATION){
Intent myIntent = new Intent();// 创建Intent对象
myIntent.setAction("com.kg.exit.broadcast");
sendBroadcast(myIntent);// 发送广播
}
return super.onOptionsItemSelected(item);
}
}
源代码地址: http://download.csdn.net/detail/kingsonl/4309569