在Android中,要在活动之间保持方法的持久性,可以使用以下方法:
// 将方法结果保存在SharedPreferences中
SharedPreferences preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("methodResult", methodResult);
editor.apply();
// 从SharedPreferences中检索方法结果
String result = preferences.getString("methodResult", "");
// 在一个活动中定义静态变量
public class MyActivity extends AppCompatActivity {
public static String methodResult = "";
// 在方法中设置静态变量的值
public static void setMethodResult(String result) {
methodResult = result;
}
}
// 在另一个活动中获取方法结果
String result = MyActivity.methodResult;
// 创建一个自定义的Application类
public class MyApp extends Application {
private String methodResult;
public String getMethodResult() {
return methodResult;
}
public void setMethodResult(String result) {
methodResult = result;
}
}
// 在活动中获取和设置方法结果
((MyApp) getApplicationContext()).setMethodResult(methodResult);
String result = ((MyApp) getApplicationContext()).getMethodResult();
无论您选择哪种方法,都需要确保在活动之间及时保存和检索方法结果。
上一篇:Android:在绘制其他应用程序设置中突出显示菜单项
下一篇:Android:在JetpackCompose中,ContentResolveraddStatusChangeListener不起作用