fua*_*adj 6 android recreate android-activity
我有一个活动可以监听偏好更改并重新加载应用程序。我正在recreate()这样做。但我不知道如何通过它传递参数,所以我求助于手动活动重新加载。
Intent intent = getIntent();
finish();
// add in the arguments as Extras to the intent
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)
这具有我想要的行为,但对用户来说,重新创建活动并不顺利,因为他们会看到活动被终止并重新启动相同的活动。我希望用户不知道该活动已重新启动。所以,我的问题是我可以使用该方法recreate()并仍然通过它传递参数。
小智 5
您可以在调用 recreate 之前设置有关活动意图的数据
getIntent().putExtra("RECREATE_DATA", "Some Data");
recreate()
Run Code Online (Sandbox Code Playgroud)
因为当您重新创建活动时会使用相同的活动实例,所以重新创建后意图中的数据仍然存在。
您可以尝试这种方式:您可以使用 SingleTop 启动模式重新启动 Activity,并处理 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");
}
}
Run Code Online (Sandbox Code Playgroud)
在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>
Run Code Online (Sandbox Code Playgroud)
onClick 将重新启动 Activity。
生命周期将是
-onclick
-暂停
-onNewIntent
-恢复时
| 归档时间: |
|
| 查看次数: |
3055 次 |
| 最近记录: |