可以通过在Activity的onCreate方法中重新启动模式为singleTop的Activity实例,从而保持当前Activity在栈顶,并避免被系统回收。代码示例如下:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, SingleTopActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(intent, REQUEST_CODE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
}
}
在上面的代码中,我们在MainActivity的onCreate方法中判断如果当前是第一次创建Activity,则启动SingleTopActivity,并将其设置为SingleTop启动模式,并通过startActivityForResult的方式等待其返回结果。SingleTopActivity可以为空Activity,只需要在其中重写onBackPressed方法让其立即结束即可,如下所示:
public class SingleTopActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
@Override
public void onBackPressed() {
finish();
}
}