Execute code every time the application begins - android

I would like to execute code every time the application begins (not only
the very first time the application begins so getSharedPreferences doesn't help).
I've tried to write the code in onStart() of the main Activity, but that code was executed everytime I entered the activity including times I back to this activity from other activities (so onStart() doesn't help).
If someone can direct me with this, I'll appreciate that. Thanks.

Create an Application class - everytime an application opens it will execute the onCreate Method.
//Note extends Application and not Activity.
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
//Put your code here.
}
Make sure you register this in your manifest -
<application
android:name=".MyApplication"
Any code you put in onCreate will execute when the app is opened.

You can use a flag,and that flag should be a public.
For example:
public boolean isFirstTime;
And your MainActivity's Oncreate()
if(!isFirsTime)
{
isFirstTime=true;
}else{
//do your stuff
}

Related

Which is better to use : A service or a translucent activity in Android?

I'm using a transparent activity as the MAIN,to test a certain variable, and depending on its value, the transparent Activity will intent a certain Activity.
Since the transparent activity will be paused after it's executed, i'm wondering if it's better to use a Service instead of the transparent Activity.
services are used for long runnig task to do in background like playing mp3 files. you can use
activity . there is no problem in that . it will hardly take to move to next activity .
you can also use a application class.This class will always be executed once before staring the launcher activity. example
create a class
public class MyApplication extends Application
{
#Override
public void onCreate()
{
super.onCreate();
// here check for your variable
//start your intent activity frokm here.
}
in menifeast give name of your class.
<application android:name="com.myname.MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name"></application>
what you can do is create a launcher activity....in its onCreate method check your variables and start the intent and finish this activity in oncreate itself. this way it is correct.
You could subclass your own MyApplication class from android Application class. In MyApplication.onCreate you can then check the variable and launch the corresponding activity,
Service is used for doing a background operation so that even if your activity loses focus the code runs without any problem. So it all depends on you, if your user close your activity while it is executing your code then go ahead and use it.

Android - Prevent onResume() function if Activity is loaded for the first time (without using SharedPreferences)

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.
Can I prevent the onResume() function from loading when an Activity is loaded for the first time, without using SharedPreferences?
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.Create a boolean variable inside your Activity
public class MyActivity extends Activity{
boolean shouldExecuteOnResume;
// The rest of the code from here..
}
2.Set it as false inside your onCreate:
public void onCreate(){
shouldExecuteOnResume = false
}
3.Then in your onResume:
public void onResume(){
if(shouldExecuteOnResume){
// Your onResume Code Here
} else{
shouldExecuteOnResume = true;
}
}
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..

How to execute a code when the application is launched

I have a litle android application where i would like to execute some code on the application launching.
How can I do this? I am a newbie on the Android developpement.
I was in a similar situation. I needed to execute a method only once but onCreate(), onStart() and onResume() methods didn't work for me because those methods are called when the device is rotated and in another situations.
So I decided to extend Application and run that method in the onCreate() of my custom application class because this is only run once per application start-up and because the tasks don't require long-running
Here is an example:
public class CustomApp extends Application {
public CustomApp() {
// This method fires only once per application start.
}
#Override
public void onCreate() {
super.onCreate();
// This method fires once as well as constructor
// & here we have application context
//Method calls
StaticClass.oneMethod(); // static method
Foo f = new Foo();
f.fooMethod(); // instance method
}
}
The next step is tell Android we have a custom Application class. We do it by referencing the custom application class in the 'android:name' attribute of the applcation tag. Like this:
<manifest ...
<application
android:name="com.package.example.CustomApp">
<activity>
<!-- activity configuration-->
</activity>
...
<activity>
<!-- activity configuration-->
</activity>
</application>
</manifest>
... For anyone to whom this may help you!
Probably it is a good idea to read the Activity life-cycle before you start to develop.... http://developer.android.com/guide/topics/fundamentals/activities.html
you can use this:
protected void onStart()
{
super.onStart();
Your code here.....
}
In android, start, execution and termination of an application can be thought of as an execution of a state machine. onStart() method is executed by the application the moment android dispatches it for execution for the first time. You can override the onStart function and use your own code in there as follows
protected void onStart(){
super.onStart();
return_type method1(...);
.
.
.
}
You may want to read about Activity: http://developer.android.com/reference/android/app/Activity.html
Android doesn't have a concept of application in the traditional sense, but a series of activities.
Put all initialization in Activity's onCreate()
Put code that you want to be run at the start of Activity in onStart()

Application class onCreate method not running on starting app 2nd time

I am using Application class to share global variables across activites and I am setting them in onCreate method of application class. When I start app variables values are set in onCreate and while using app in activities I am changing values of varables. When I exit app and start it again I am getting old values, the last values of variables set in activities. Thats mean onCreate of Application not running on starting app again. This is code in onCreate method of Application class.
#Override
public void onCreate() {
super.onCreate();
application = this;
category = 12;
subCategory =22;
}
It looks like old application object is still in memory and it is not calling onCreate on starting app 2nd time.
What is need to be done so that onCreate of application class run again or where to initialize variables in application class so that code runs everytime.
please declare your application class name in manifest file.
like below
<application
android:name="com.tt.app.TTApplication"
android:label="#string/app_name"
In the Application class, the onCreate() method is called only if the process was ended when you exited the application. Usually the process is stopped when the system needs memory or if you exit the app using the back button instead of the home button. However, you cannot rely on it being terminated.
However, the right way of passing parameters between activities are intents or preferences. In your case, I have the feeling that preferences is the way to go.
If you really want to kill your process when exiting the application, you can call
System.exit(0); when the user presses the back key on your first activity. This is definitely not recommended since it means fighting against the way the Android OS works and might cause problems.
More on this here: Is quitting an application frowned upon?
There is probably an instance of your application still in the memory.
Recheck your life cycle methods and make sure that the application is exiting properly.
Also check if any of your activities are leaking memory.
I had the same problem with my app where onCreate() method of Application class just triggered for the first time when my app is loaded. Daniel's solution of using System.exit(0) did the trick but this solution lead me to another problem. After using System.exit(0), onPause(), onStop() and onDestroy() method of my foreground activity did not get called.
Well, that was a reasonable behavior for an app because If you use System.exit(0) then you application will be removed from System's process queue and there will be no way for an android to execute onPause(), onStop() and onDestroy() method for my foreground activity.
The workaround I used for this problem was to finish my activity when back button is pressed and after some time killing my applications process like below:
public void killApp(){
final Thread threadKillApp = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "Going to kill app");
android.os.Process.killProcess(android.os.Process.myPid());
}
});
threadKillApp.start();
}
Calling killApp() method just after calling finish() on my activity did the job.
Check the Activity life cycle. Do what you want in onResume() instead.
try to use onStart() method or onResume().
Your onCreate method should look like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(someView);
}
your onResume Method should look like this:
#Override
public void onResume() {
super.onResume();
variable = someVariable;
}

android log out help

I have an application that has a user log in and log out. On a log in it tells my DataBase that the user is online. Problem I am having is that when the user doesnt use the app for a while and the processor kills my app is there a method or something where i can run my last piece of code to log them out? I looked at the android life cycle and i cannot use destroy because that only ties with that activity. Thanks!
I found a solution for this - not perfect but worked for me.
1.) Create a service to run in the background which is started when the first activity is created.
2.) Each activity binds to this service so it can "check-in" (i.e. it is alive and onPause) hasn't been called)
3.) In each activity register a broadcast receiver that listens for an intent fired by the service on a regular basis.
4.) On receiving the chech-in intent, it calls a service method which basically lets the service now there is an activity that is still alive (I tent to only respond to the intent if it had windowFocus
5.) If there is a check-in the service sleeps and then re-requests a checkin, if there was no check-in it sleeps for a shorter period of time, before re-requesting a check-in, if none respond then the app logs out. (The reason for the second re-quest when no check-ins were found was to account for issues surrounding check-in during an activity transition, i.e. starting a new activity and closing the current one).
As I said this isn't the nicest way to do it but seems to work for my needs so far.
why can't you use onDestroy method of your activity? if you have a lot of activities, you can create your own base activity class and derive all your activities from this base class.
public abstract class BaseActivity extends Activity {
....
#Override
public void onDestroy() {
super.onDestroy();
// do your stuff here
}
}
and thenm create all your activities like this:
public class YourActivity extends BaseActivity {
...
}
In AndroidManifest you've got name. Now create
public class MyName extends Application {
}
this is your Application class which is automatically created once user open your app. Now simply override onTerminate() method inside MyName class.
#Override
public void onTerminate() {
user.logOut();
super.onTerminate();
}
You can use your MyName class in every Activity simply with this code:
MyName myName= (MyName) this.getApplication();
myName.logUser(user);

Categories

Resources