Android-如果是首次加载“活动",则禁止onResume()函数(不使用SharedPreferences) [英] Android - Prevent onResume() function if Activity is loaded for the first time (without using SharedPreferences)

查看:285
本文介绍了Android-如果是首次加载“活动",则禁止onResume()函数(不使用SharedPreferences)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的应用程序中,当我第一次加载Activity时会触发onResume函数.我查看了活动生命周期,但没有找到解决方法以防止这种情况发生.

In my current application the onResume function is triggered when I load an Activity for the first time . I looked into the Activity Lifecycle, but I didn't find a way to prevent this from happening.

是否可以在不使用SharedPreferences的情况下首次加载活动时阻止onResume()函数加载?

Can I prevent the onResume() function from loading when an Activity is loaded for the first time, without using SharedPreferences?

推荐答案

首先,正如RvdK所说,您不应该修改Android Activity生命周期,可能必须重新设计活动行为才能使其符合要求.

Firstly, as RvdK says, you should not modify the Android Activity lifecycle, you probably have to re-design your activity behavior in order to be compliant with it.

无论如何,这是我所看到的最好的方式:

Anyway, this is the best way that I see:

1.在活动"中创建一个布尔变量

1.Create a boolean variable inside your Activity

public class MyActivity extends Activity{
  boolean shouldExecuteOnResume;
  // The rest of the code from here..
}

2.在您的onCreate中将其设置为false:

2.Set it as false inside your onCreate:

public void onCreate(){
  shouldExecuteOnResume = false
}

3.然后在您的onResume中:

3.Then in your onResume:

public void onResume(){
  if(shouldExecuteOnResume){
    // Your onResume Code Here
  } else{
     shouldExecuteOnResume = true;
  }

}

这样,您的onResume不会第一次执行(shouldExecuteOnResume为false),而是在加载该活动的所有其他时间执行(因为shouldExecuteOnResume为true). 如果该活动在下一次被加载时被用户或系统杀死,则将再次调用onCreate方法,因此将不执行onResume等.

In this way your onResume will not be executed the first time (shouldExecuteOnResume is false) but it will be instead executed all the other times that the activity is loaded (because shouldExecuteOnResume will be true). If the activity is then killed (by the user or the system) the next time it will be loaded the onCreate method will be called again so onResume will not be executed, etc..

这篇关于Android-如果是首次加载“活动",则禁止onResume()函数(不使用SharedPreferences)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆