您可以尝试这种方式:您可以使用作为 SingleTop 的启动模式重新启动活动并处理 onNewIntent(Intent intent) 方法。这样,您将重新启动活动并发送意图,同时该活动不会被杀死,即不会调用您的活动的 oncreate。
public class MainActivity extends Activity implements View.OnClickListener {
Button btn ;
String mRelaunchData ;
public static String TAG = "RelaunchMainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(this);
Log.e(TAG, "onCreate called");
}
@Override
public void onClick(View view) {
Log.e(TAG, "onClick called");
Intent intent = new Intent("relaunch.activity.ACTIVITY_SELF_START_INTENT").setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("RESTART_DATA", "This is relaunch of this Activity");
startActivity(intent);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e(TAG, "onNewIntent called");
mRelaunchData = intent.getStringExtra("RESTART_DATA");
Log.e(TAG, "mRelaunchData =" + mRelaunchData);
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume called");
if(mRelaunchData != null){
Toast.makeText(MainActivity.this, mRelaunchData, Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPause() {
super.onPause();
Log.e(TAG, "onPause called");
}
@Override
protected void onStart() {
super.onStart();
Log.e(TAG, "onStart called");
}
@Override
protected void onStop() {
super.onStop();
Log.e(TAG, "onStop called");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy called");
}
}
在 AndroidManifest.xml 中
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="relaunch.activity.ACTIVITY_SELF_START_INTENT" />
<category android:name = "android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
onClick 将重新启动 Activity。
生命周期将是
-点击
-onPause
-onNewIntent
-onResume