比如有ActivityA, ActivityB,在ActivityB中关闭ActivityA。
解决方案:
1.在 ActivityA 里面设置一个静态的变量instance,初始化为this,在 ActivityB 里面, ActivityA.instance.finish();
2.也可以通过ActivityManager
ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
manager.restartPackage(packageName)
代码:
ActivityA:
public class MainActivity extends Activity {
public static ActivityA instance = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitya);
instance = this;
Intent intent = new Intent();
intent.setClass(ActivityA.this, ActivityB.class);
ActivityA.this.startActivity(intent);
}
}
ActivityB:
public class ActivityB extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityb);
}
// 返回键
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) { // 如果是手机上的返回键
ActivityB.this.finish();
ActivityA.instance.finish();
}
return super.onKeyDown(keyCode, event);
}
}