Life cycle of Android Application/process? - java

I am writing an android application. In the application there are 4 activities.All the activities are mutually independent.
In my application i want to use a socket communication and a service. Both of them starts when the first activity is launched and should be stopped when the last activity exits. The starting activity is preset, so no problem in the starting. But the last activity is random. In this situation how should i stop the service and close the socket?? Is there any callback when the "Application" exits? I have seen the android activity life cycle, But it doesn't says anything about the whole process....

How about using AIDL-interface to a service and let each activity register/unregister. Then let the service count number of activities active and when the counter reaches zero close the socket and exit.

onCreate and onDestroy - bracket the entire life of the app. This pair is called when the app is loaded into memory or unloaded from memory. These two bracket the entire lifetime of an activity. When it is first loaded the onCreate is triggered and when the app is disposed of onDestroy is triggered. You clearly have to use these two to setup and destroy and resources which are needed for the entire lifetime of the app - although in practice things can be more subtle. The system can stop the app without calling the onDestroy and can restart the app triggering an onCreate event.
onStart and onStop - bracket any period that the app is visible. It could be that the app is behind say a modal dialog box. The app is visible but not interacting with the user. This pair of events can be triggered multiple times during the entire lifetime of the app. Simple apps can mostly ignore the onStart and onStop events because the app is still in memory and doesn't loose any resources or state. The main use of onStart and onStop is to give the app an opportunity to monitor any changes that might affect it while not interacting with the user. To confuse the issue even more there is also on onRestart event which occurs before the onStart event but only if this isn't the first time the app has fired the onStart - that is this is a true restart.
onResume and onPause - bracket the period that the app is in the foreground and interacting with the user. Again this pair of events can happen multiple times during the entire lifetime. The onResume event occurs when the app is in the foreground and doing its usual job. The onPause event occurs when the user switches away to another app for example.
You can learn a lot about lifecycles in this Adventure: Have a look at it: http://www.i-programmer.info/programming/android/5966-android-adventures-lifecycle-and-state.html
Edit:
Maybe this will help you: How to handle activity life cycle involving sockets in Android?
And here is a good guide on how to use them:
http://tacticalnuclearstrike.com/2011/03/a-way-of-using-sockets-in-android/

Related

How to know when an app is killed after being in recents for a long time?

Which function is called when an app is killed by keeping it in recent apps list for a long time?
I am not asking about when an app is killed by swiping app from the recents list.
There is no such function in Android.
When user closes the app, the process is terminated with no notice. Even Activity's onDestroy method is not guaranteed to be called. Only when you explicitly call finish().
If you use ViewModel that is tied to the starting Activity's lifecycle, you can try to use onCleared() method, which is called always when ViewModel is no longer used and will be destroyed. See: https://developer.android.com/topic/libraries/architecture/viewmodel
There is no such function.
At the point when the system decides to kill your process, it will do so immediately without calling any more of your code beforehand.
Another answer suggests using ViewModel, but this won't work if you actually need a reliable signal. It is not guaranteed to trigger, and it may trigger in other circumstances (such as the user backing out of the activity, but the app process not being killed).

One activity that runs the whole time

I want to calculate how much time a user spends on my app. I thought of doing so by using chronometer. So is there an activity or something that runs always when the user is using any part of my app? or should i start and stop the timer in each and every activity?
That's not the right way to do it. Use Activity lifecycle callbacks (https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks) to determine when one of your activities is paused/resumed. When one is resumed, start the timer. When one is paused, end it.
Use Service instead of Activity.
Services run in background and you can access them all the time.

How is an Android Activity recreated when the screen is rotated?

I'm a newbie Android developer. I know that when the screen orientation changes, the Activity is re-created and onCreate() is called again. What I couldn't find online, however, is how exactly the original Activity is destroyed. If some code called by onCreate() is in the middle of running, does that code just stop, or does the system wait for that code to finish before rotating the screen and calling onCreate() again? Thanks.
Activity's onCreate() is called everytime when the orientation changes and you should take care of your asynchronous task because the system does not wait, but you can avoid the re-creation of Activity by adding configChanges attribute of Activity in your AndroidManifest file in the activity tag.
android:configChanges="keyboardHidden|orientation"
According to the official documentation on configuration changes, once a device rotation is detected or the activity is started for the first time, onCreate() is called; you should assume that for all intents and purposes the onCreate() method will complete its execution before another screen rotation triggers activity recreation. Any code executed in your onCreate() should be done instantaneously since it shouldn't block your UI.
When rotating a screen we call it one of the Configuration Changes, it includes situations such as screen orientation, keyboard availability, and language changes. As quoted from Android official documentation here onDestroy() will be called then onCreate().
Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate()).
But if there was any code executing on the main thread will have to finish (not other threads) and Android gives you time to save the activity data which you can receive on onCreate() when the activity is restarted. It does so by calling the method by calling the method onSaveInstanceState() as explained here in the documentation.
To properly handle a restart, it is important that your activity restores its previous state through the normal Activity lifecycle, in which Android calls onSaveInstanceState() before it destroys your activity so that you can save data about the application state. You can then restore the state during onCreate() or onRestoreInstanceState().
So the whole issues of code in the activity is that it will wait for the code to finish if it were executing on the main thread and if the code taking too slow it may make configuration changes very slow as it is discouraged in the documentation to make huge tasks in the main thread (for instance http requests).
This whole answer and descriptions and quotes has been taken from Android Official Documentation Guide, you can visit it for reference and more descriptions on configuration changes.

Good practice of using android activities

I completed few android apps successfully but always I feel that I am not following the best practices of android developnment.
Few things which makes me feel developing a 100% complete android app is tough are
1. Making sure that my app is following all memory management stuffs
2.Making sure that my app is not going to crash
3.This one is always a big confusion for me-
I put all my code in oncreate() method including event listeners, phonestate listeners(If I require) etc..
What is the use of other methods like onResume(), onPause()... (I understood the concept of when they are called)
Should I stop all my event listeners in onPause() or by default android clears it?
Can I put all my event listener in onResume()?
Check dev Link
when ever over activity come in on stack again like previous it was not delete from stack then on resume is calling like if u want to see any list from any web service then after light off and again screen light is on then onresume() is call and u can call that webservices here and arrange list view with update values.
when ever your application go in pause mode then onpause() will call
you can follow above link i think your all query regards this will solve
The best reference for activity lifecycle callbacks is probably the the Android developers guide, and in particular this part:
http://developer.android.com/training/basics/activity-lifecycle/starting.html
Should I stop all my event listeners in onPause() or by default android clears it?
Either there or in onDestroy() but it depends what you're using them for; if you want the listener to listen even while that activity is paused or stopped then obv. stopping in onDestroy() is better.
Can I put all my event listener in onResume()?
It depends, onCreate() is only called once when your activity first starts up, whereas onResume() is called when your activity starts as well as every time your activity comes back from being paused or stopped. So if you stopped listening in onPause() then you probably want to start listening again in onResume(). If you stop listening in onDestroy() then you probably want to start listening in onCreate().

Android dialog management

I'm developing an android app (if you want more info http://www.txty.mobi) and I am having some problems with dialogs management. I'm quite new to Android so the way I'm doing things completely wrong. If the case please just say so pointing me to the right documentation to follow.
Background:
The main blocks of the app so far are one activity and one Service (which derives from IntentService).
The actvity needs to interact with the service in just two occasions: start/stop the service. The intent service will self regulate its lifetime using the AlarmManager.
A typical flow when clicking on start/stop:
1) the activity on its onResume registers a broadcast receiver to events sent by the service (unregisters it in the onPause)
2) the activity starts a indeterminate progress dialog
3) the activty sends a single shot alarm event (either start or stop) which will be send **straight away to the service
4) the service does what it needs to do to start
5) the service emits a broadcast event basically saying "done"
6) the activity receive this event and gets rid of the dialog.
The Problem:
The activity can lose its foreground status let's say if the user switches focus or a call is received, so the onPause method is called (at this point the activity could even be killed by the system to claim memory). obviously if this is the case the activity will never receive its broadcast event because the receiver has been unregistered. This will leave the app in the awkward situation, when the activity is brought again to the front, of having a dialog that you can't kill nor will never get rid of.
The (possible??) solution:
The way I am handling this now (apart for keeping the broadcast receiver in place) is by creating a utility class that uses preferences to keep track of which operations are being executed and their status:
Activity
- in the onResume using my utility class gets the list of operations the activity is waiting for
- check their status
- if they are completed perform some actions accordingly (in my case get rid of dialog!)
- delete the operation from the preferences.
- just before asking for a operation to the service it saves it to the preference using my utility class.
Service
perform operation and save state of the operation to the preference using my utility class.
emit broadcast.
Disasters happen!
Now this saves me in a normal situation, but if a disaster happens (i.e. with the task killer app you kill everything) the service might be killed before it can save the status of the operation I am stuck as before (the activity will think the operation is still going on so it won't touch the dialog). So as for now I add a Dismiss button to very dialog just in case :)
Now all of this looks too complicated for what I think should be a fairly common thing to do. That's why, as said at the beginning of the post, I might (very likely!) be completely wrong.
Any ideas? Apologies if this question has been asked already, I looked around but didn't find anything. Please point me to any resource online explaining this.
Thanks and sorry for the lenghty post :P
Luca
Have you tried using a StickyBroadcast? This caches the latest broadcast, so it can be received onResume. Please see this post.

Categories