你可以尝试这种方法:你可以将启动模式设置为SingleTop并处理onNewIntent(Intent intent)方法来重新启动活动。这样,你就可以重新启动活动并发送意图,同时不会杀死该活动,即你的活动不会被创建。
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。
生命周期将是:
-onclick
-onPause
-onNewIntent
-onResume