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

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;
}

Related

Hook to close method on an application level

I want to perform logic whenever my Android app is in the process of being closed, so to avoid duplicating the same logic on each Activity.
Similar to OnCreate() below, which is invoked whenever the app is starting, I need the close/terminate method.
public class Application : Android.App.Application
{
public override void OnCreate()
{
}
}
Most of the times your Application class will not know that it is going to shut down because usually it is just killed by the system. You can hide activity but you can't hide application since it is always there (as long as process runs). And if user (or system) decides to manually kill it you will not get any chance to save your data since it might be time consuming. So the best way would be to call custom method in Application from your Activity's onStop() and save everything you need. And it will be a good idea to save data in background thread.
In activity class:
#Override
protected void onStop()
{
((CustomApplication)getApplication()).onCloseCustom();
super.onStop();
}
In your application class
public void onCloseCustom()
{
//do whatever you need
}

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.

If an application is not closed (running in background) , does it cause application crash?

I have an application works well in emulator and mobile but if we close the application by clicking on exit button of the phone(not from application).and after few hours we are reopening the application, it gets opened from middle of the application(not from the first screen).and after using that app some times it gets hanged and message is displayed 'unfortunately app has stopped '. Is this mobile problem or application problem.
I suggest reading the Activity documentation.
The Android OS has its own application lifecycle management.
Each activity is kept "alive" until its onDestroy is called. For example, the OS can keep an activity alive for several hours and then kill it when there is not enough memory to perform other tasks.
What happens in you case is most likely that the same activity re-runs when you open you app again (in the emulator the activity is probably killed before) and you're in a bad state since probably some of the objects were disposed or re-initialized.
The right thing to do is use some of the other state callbacks, such as onPause/Resume to allocate/dispose resources used by the activity.
You code might look like this:
public class SomeActivity extends Activity
{
public void onCreate()
{
super.onCreate();
// Do some object initialization
// You might assume that this code is called each time the activity runs.
// THIS CODE WILL RUN ONLY ONCE UNTIL onDestroy is called.
// The thing is that you don't know when onDestry is called even if you close the.
// Use this method to initialize layouts, static objects, singletons, etc'.
}
public void onDestroy()
{
super.onDestroy();
// This code will be called when the activity is killed.
// When will it be killed? you don't really know in most cases so the best thing to do
// is to assume you don't know when it be killed.
}
}
Your code should look something like this:
public class SomeActivity extends Activity
{
public void onCreate()
{
super.onCreate();
// Initialize layouts
// Initialize static stuff which you want to do only one time
}
public void onDestroy()
{
// Release stuff you initialized in the onCreate
}
public void onResume()
{
// This method is called each time your activity is about to be shown to the user,
// either since you moved back from another another activity or since your app was re-
// opened.
}
public void onPause()
{
// This method is called each time your activity is about to loss focus.
// either since you moved to another activity or since the entire app goes to the
// background.
}
}
bottom line: always assume the same activity can re-run again.
Actually, that particular application is not closed properly. It is application error only.

Detect termination of Application, Android

I need a method to detect when my application is closing, so that I can tell a web-server to clear my session variable that it's storing. Is there any way to do that?
I'm assuming your application extends Activity.
You could use the onDestroy() method:
From the docs :
onDestroy() is The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
Your code would look like this:
public class YourAppActivity extends Activity {
...
...
#Override
protected void onDestroy() {
super.onDestroy();
//clear your session variable.
//you may want to do this quick, and on another thread
//to prevent android from killing your app
}
}
check
Activity Lifecycle and
i think you can do it on onDestroy()
You could try onDestroy() which is run when the app is being destroyed by the system or onStop() when the app loses visibility (often prior to destroying). You code would then look something like this:
public void onDestroy() {
super.onDestroy();
//Enter your code here to do stuff
}
However, on destroying your app the variables used by it will be destroyed along with it.
See: How to release or clear the value of variable or object?
For this you have to create static variable for counter of integer type. On OnCreate method Increment variable by 1 and on OnDestroy() Method decrement the variable value. and on OnDestroy() Method check the static variable value is 0 or not if it is 0 then call the webservice to clear the session
I would use the Activity's onDestroy() method checking whether the user is terminating the app or the OS is killing the process' activities because of low memory with the isFinishing() method. To deploy the "Destroy web session" logic, you could start an IntentService to start this action.
Hope it helps.

Android - How to track app Resumes only when you exit and come back to the app?

I have an issue. For analytic purposes I need to track when the APP (not activity) is resumed. The problem I have now is that if I put the tracker on the OnResume event of an activity, it will get fired every time the user goes back and forth on different activities.
How can I avoid that? How can I track the real "Application Resume," (when user actually exits the app and come back) and not the activity resume?
Any ideas is greatly appreciated. Thanks.
I encountered the same problem and solved it by creating base activity :
public class mActivity extends Activity{
public static final String TAG = "mActivity";
public static int activities_num = 0;
#Override
protected void onStop() {
super.onStop();
activities_num--;
if(activities_num == 0){
Log.e(TAG,"user not longer in the application");
}
}
#Override
protected void onStart() {
super.onStart();
activities_num++;
}
}
all the other activities in my app inherited mActivity. When an activity is no longer visible than onStop is called. when activities_num == 0 than all activities are not visible (meaning the the user close the app or it passed to the background). When the user start the application (or restarting it from the background) onStart will be called (onStart is called when the activity is visible) and activities_num > 0. hopes it helps...
Use the Application object of your app (see http://developer.android.com/reference/android/app/Application.html). If you create a custom Application class and configure it in your AndroidManifest.xml file you can do something like this:
Start tracking in the onCreate() of the Application object.
Instrument all your Activities so their onPause() and onResume() methods check with the Application object and see if they are the first Activity to run, or if they are continuing a previously running instance of the app.
Stop tracking in the onDestroy() of the Application object.
To a certain degree most of the analytics packages (Flurry and their ilk) do something similar to this. You'll need to do a little state machine work to get this to work right, but it shouldn't be too complicated.
Instead of OnResume(), hook into the OnCreate() event of your main activity.

Categories

Resources