How to execute a code when the application is launched - android

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()

Related

super call in Service lifecycle

When I was reading this link https://developer.android.com/guide/components/services#LifecycleCallbacks,I came across this statement
Note: Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods.
Can anyone explain why it is not required to call superclass and on what scenario we can add superclass implementation?
Thanks
In the activity lifecycle the callbacks are made because we need to run the existing code on those methods of the Activity class.
For example
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
// your code
}
In this method we say the compiler to not only run our code but also the existing code in the onCreate method of the Activity class. The existing code takes care of assigning the context to the activity, setting the actionBar etc. If you wanna know more about what the existing onCreate method code does, you can navigate through that method in the Activity class.
But in the case of Service we need not run the existing code ( of course there are no existing code in those methods ) and the system itself takes care of what to do and only notifies us about what lifecycle the service is going through so that we can code according to the lifecycle our service is in.
For example
#Override
public void onDestroy() {
// You can make a toast here to notify the user that the service has ended
}
This method in the Service class notifies that the service is being destroyed. You can navigate through this method in the Service class and see no code has been written on that method. So we can conclude that the method is only notifying us about the destroying of the service.
But you can still make a super call on the method, Like below
#Override
public void onDestroy() {
super.onDestroy();
}
But we have no changes in the running of the code since the onDestroy method in the super class is empty. More precisely we don't need the existing code (in this case it's empty) to what we expect that to do.
For your last question,
You should implement a super call when you wanna run the existing code. If you just wanna know if the method is called and you don't wanna run the existing code but only your code on the subclass you should not implement a super call

Android application: modifying firebase database before app destroyed

I am trying to modify my firebase database when my app is destroyed, that means when I remove the app from the list of recent running app or when I click on Home button ,but I don't know how to do this, I tried to do that in onDestroy() method of every activity but it doesn't work.
This is my onDestroy() method :
#Override
protected void onDestroy() {
super.onDestroy();
FirebaseDatabase.getInstance().getReference().child("users").child(encodeEmail(mAuth.getCurrentUser().getEmail())).child("status")
.setValue("destroyed") ;
/*Toast.makeText(ContactsActivity.this,"closing app",Toast.LENGTH_LONG).show();
MyApp app = (MyApp)getApplication() ;
app.setUpBeforeClosing();*/
}
On Destroy Documentation
Do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.
Either use OnPause or Use a service to write data.
Add this in manifest
<service
android:name="com.myapp.MyService"
android:stopWithTask="false" />
Now in your MyService service, override method onTaskRemoved. (This will be fired only if stopWithTask is set to false).
public void onTaskRemoved(Intent rootIntent) {
//save data to firebase
//stop service
stopSelf();
}
reference
Do you have BaseActivity or not ?
I think you just forgot to add this line in the right activity.
I suggest you to create BaseAvtivity.java class and extend all your activities from it, and the BaseActivity would extends AppCompatActivity and then override tbe lifecycle methods in BaseActivity and set new value in onDestroy method.

Execute code every time the application begins

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
}

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