I need to detect the first time an activity is called every time the user launches the app:
... so "do something" has to be called only if the app was closed (or killed) and then be launched again.
There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings! a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever ...
It is important to check that the first activity which opens when the app is launched is MainActivity. java (The activity which we want to appear only once). For this, open the AndroidManifest. xml file and ensure that we have the intent-filter tag inside the activity tag that should appear just once.
in short onCreate is called first and when you comeback from an activity onResume will be called. onResume will also be called the first time as well.
Android is developed by a consortium of developers known as the Open Handset Alliance and commercially sponsored by Google. It was unveiled in November 2007, with the first commercial Android device, the HTC Dream, being launched in September 2008.
I usually use static boolean
variable inside the activity as a flag. Then, inside onCreate()
, test the variable; if it's true
, do something and flip the flag.
public class MainActivity extends Activity {
private static boolean RUN_ONCE = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
runOnce();
}
private void runOnce() {
if (RUN_ONCE) {
RUN_ONCE = false;
// do something
}
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With