Do something when app starts?

情到浓时终转凉″ 提交于 2019-12-13 22:28:50

问题


I have a very quick question.

Whenever the user downloads my app, for some reason the volume is at zero. I want to raise the volume whenever the user enters the app for the first time, and update something. Whenever the app is created, I want the users volume to be increased, and the user can change that later. If the user leaves the app (home menu) and comes back, that code should not execute.

So, I thought I would use the Application class:

That didn't work, since to do the update I mentioned earlier, I would need to call a non-static method. To do this, I would create an object of the class where the method is, and call it from there.

The problem with that is that the method has never been called before, and it has lots of null objects then. So, there will be a null pointer exception.

So, how can I achieve this? Only have the volume increase if the user has come back after closing the app or it is the first time the user is downloading the app. Doesn't matter if the app is still open in background. I also need to call another method from there when the app starts...which would get a nullpointerexception.

So now I am lost. How can I achieve this?

Thanks,

Ruchir


回答1:


Actually changing volume without any user interaction would be a bad user experience. However for answering this question. You can use SharedPreferences

When your app starts:

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences("com.example.myapp.PREFERENCE_FILE_KEY", Context.MODE_PRIVATE);
int defaultValue = 0;
long openedState = sharedPref.getInt("isAppOpenedBefore", defaultValue);

if (defaultValue == openedState)
{
   // First launch
   // Change volume
   // Writing app already opened state
   SharedPreferences.Editor editor = sharedPref.edit();
   editor.putInt("isAppOpenedBefore", 1);
   editor.commit();
}



回答2:


You can take a look at the Activity Lifecycle.

http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

You can use the onStart method in you launcher activity and make sure that everything is not null.

If this should happen only at the first start of the app per device you can set a sharedPreference at the ned of your on start to true and in the beginning of onStart you can check for that value. You can check if SharedPreference has that specific value.

http://developer.android.com/reference/android/content/SharedPreferences.html



来源:https://stackoverflow.com/questions/33888178/do-something-when-app-starts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!