Android - 如果第一次加载Activity,则阻止onResume()函数(不使用SharedPreferences)

Jac*_*ack 8 android onresume sharedpreferences android-lifecycle android-activity

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

我是否可以在第一次加载Activity时阻止加载onResume()函数,而不使用SharedPreferences?

The*_*ant 28

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

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

1.在Activity中创建一个布尔变量

public class MyActivity extends Activity{
  boolean shouldExecuteOnResume;
  // The rest of the code from here..
}
Run Code Online (Sandbox Code Playgroud)

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

public void onCreate(){
  shouldExecuteOnResume = false
}
Run Code Online (Sandbox Code Playgroud)

然后在你的onResume:

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

}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您onResume将不会在第一次执行(shouldExecuteOnResume是错误的),但它将在活动加载的所有其他时间执行(因为shouldExecuteOnResume将是真的).如果活动随后被(由用户或系统)杀死,则下次加载时onCreate将再次调用该方法,因此onResume不会执行该等方法.

  • 为了避免使用静态使用`android:launchMode ="singleTask"`让你的活动单一任务.这将使它只创建一次并在每次调用此活动时重用,并使shouldExecuteOnResume保持非静态 (3认同)