I am looking for a way to logout the user of my app automatically when the application has been terminated. I dont believe there is anyway to do this as only the activities have an onTerminate() function call. I am coming from an ios background where i an app, i could call a logout() function when the user entered the background. Is there a similar sort of parallel for android?
The reason i am looking for this option is because i have a global helper class that extends Application to store some user credentials and other info. If the application gets terminated by the os, this data is lost from what i have read. So i would like to force the user to log back in again to repopulate this data if it was destroyed.
Save user credentials to shared preference, Then when press logout button clear data in shared preference and finish the activities and cancel all background services related to your app
Related
On Android, it is possible for users to use the Settings -> Application Manager -> App -> Clear Data feature and clear all the stored data for the app. However, if the user uses the app switcher to switch back to the app it will switch back to the activity last used. In some cases, say with an app that requires login, the activity will be inappropriate for the case where there is no data. How should application handle his case? Should each Activity be derived from a base Activity class that checks if the data has been deleted and then launch the appropriate Activity (say, the login Activity)? Is there a more elegant solution than that?
Instead of checking if data has been deleted, just check if the user is signed in. If he isn't, you can just send him back to the login screen as you suggested.
In any case, if you are using oAuth, or ever intend to implement it for login, checking if the user is logged in should be implemented since the oAuth tokens eventually expire. In this case, no data has been deleted, but the user is no longer signed-in, which would lead to them getting stuck in the inappropriate Activity anyway.
Just create a super-class for your ActivityThatRequiresLogin that will check if the user is logged in, and have all ActivityThatRequiresLogin extend that class. Then, you can call super whenever the onCreate and onResume method is called.
If the user wipes their data, they are automatically signed out, so all you have to do is check if they're signed in or not.
Pressing Clear Data stops your app's process, so your code will not be running.
Unfortunately there is no way to catch intent of such action unless you'r a system app.
The best practice way to handle this situation would use a SharedPreference mechanism and a base activity class.
I'm saving some data into sharedpreferences and my problem is the data remains even when the App is closed, and even if the pda is reset
Another question about the lifecycle, my App should keep working in background and it does if i press the "menĂº" button of my pda, choose other apps in the meanwhile, etc... But if I press the "back" button, it executes the ondestroy method and the App doesn't keep working.
Thanks!
sharedpreferences are designed to do just that. persist data between app executions..
-- http://developer.android.com/guide/topics/data/data-storage.html#pref
if you want your app to remain active in the background you need to have it run as a service.
-- https://developer.android.com/training/run-background-service/create-service.html
The sharedpreferences are intented to stay when the app is closed. It's just an xml-file storing your data. If you don't need some of the values you either may reset them in the onCreate of your Base-Activity or define a global class that extends Application and store your data there in global variables.
I want to do something when my application destory.But now, user may be use some other app to kill my app, at that time, i dont know what function will be called.I read the document and try a lot...but the onTerminate() can't do on android decive.
so how can i detect my application is killed? there are some functions will be called when app be killed? or some BroadcastReceiver will be send?
Depending on how the app is destroyed, the Android system might call onDestroy(). However, this is not guaranteed. For example, if the user uses the standard App Management utility to "Force Close" your app, onDestroy() will not be called.
If you want to save the state of your app, you need to do so during normal operation. If you need to store data temporarily, you can override onSaveInstanceState(). If you need to store data more permanently, you can use either SharedPreferences, a SQLite database, or a file. See the Android Developer docs for more details.
I also suggest that you read the Android Developer docs about the Activity life cycle.
I think what you're trying to do runs opposite of why someone would be killing an app.
When the user is trying to purposely close the app, that user does NOT want the app to do anything more.
Why do you need to check if the user is killing the app? If you need to save data, then you should design your app to save data when the user is actively using your app.
I'm asking this question because I want to be sure which is the best way to store the user "logged in" / "logged out" state in my android application.
Here is what I am doing. In my application I connect to the server, send him username and password and if everything is ok it returns me OK. So now I want to be able to save the user logged in state all over my application because I need to change the content depends on that if user is logged in or not.
And the other thing is that I need to be able to save the user's login state, so the next time when he start the application he will be automatically logged in.
Any suggestions or ideas which is the best way to do that?
I made a little research over internet and find a few ways to do that :
MyApplication class which extends android.app.Application
SharedPreference
Or maybe a SQLite
There can be many reasons when your app looses focus, like pressing home button incoming call, etc but no matter what happens your onPause method of current Activity is called so what you have to is-
Override onPause method of every activity
Use SharedPreference to save the state of Application
I use static classes or SharedPreference - it'is easy and it's works.
SQLite it not good way (in my opinion)
your option SharedPreference is the perfect one in this condition as you need to store only boolean and you will access if often in your app to change the content.
The problem with storing the state on the device (using either the SharedPreferences or SQLite) is that the user can manipulate it. So if you simply store "isLoggedIn" in your SQLite-Database, this entry can be manipulated using dpms (for example).
So if you need to store the state, you should use the Application-class (this can be manipulated, too, but it's harder to do so). If the user closes the application, you destroy the state-variable so he needs to do the login when the application is opened the next time.
For usability, you could store username and (if the user wants so) the password.
Also, if you have a web-service that you use to check if the users login-data is correct, why don't you use for example OAuth to authentify the user on the server and deliver the content from it? This would basically make your application a pure "client".
SharedPreference is the best option to access single value in terms of timing which i observe to be true as compared to sql lite.
I'm trying to implement some automatic logout code for my Application on Android.
I need to detect if all the activities belonging to an Application have entered the background as opposed to working with onPause() and onResume() for each individual activity. iOS has a helpful applicationDidEnterBackground: method that I could utilize, but I'm unable to find a similar function in Android's Application class.
One approach seems to be to have an AtomicInteger counter and increment it once an activity becomes visible and decrement it when it's finished or onStop() gets called. So if the counter becomes zero, I can start a service that runs in the background and handles the logout. Is this how it's usually done?
There is no global callback for this, but for each activity it is onStop(). You don't need to mess with an atomic int. Just have a global int with the number of started activities, in every activity increment it in onStart() and decrement it in onStop().
You really don't want to log out the user when the "application" goes in the background, any more than you log out the user of a Web app when the user switches to another tab or minimizes their browser window for a moment. If you were to do either of those things in a Web app, your users would consider your Web app to be an epic fail. Similarly, if the user gets a phone call with a wrong number, or the alarm clock goes off, they'll be rather irritated with you if they have to immediately go back in and sign in when they were just using your app 5 seconds ago. Here, by "irritated", I mean one-star ratings on the Market and nasty comments.
A Web app automatic log out is based upon inactivity, using a server session cookie.
Similarly, when I build a secured Android app, I'll be implementing an inactivity-based mechanism, perhaps something like this:
Step #1: Create a Session class with a static singleton instance. The Session object holds the last-accessed timestamp.
Step #2: In each activity's onResume(), see if the Session singleton exists. If not, it's a brand-new process, so if this isn't the authentication activity, immediately do a startActivity() to bring up the authentication activity.
Step #3: Back in each activity's onResume(), if the Session object exists, call something like extend(). This would return a boolean, true indicating the session is still good (and the timestamp has been updated to now), false otherwise. If it returns false, do the same stuff as if the Session object were null.
Step #4: Your authentication activity, upon success, sets up the singleton Session object with the current timestamp.
Step #5: Your Session class' extend() method is where you make the determination if the session is too old.
No matter how the user gets into your application, if the session is too old (or it's a brand-new process), they are forced to authenticate. Yet, if the user briefly is interrupted -- where you and/or the user can define "briefly" -- they don't have to re-authenticate.
I think your suggestion is probably the best way to go. Unfortunately I don't think there's an API call to detect if your app is in the background or not. You'll just have to manipulate the onPause() and onResume() methods. Just keep in mind that you'll need need to account for transitions between activities, so once your AtomicInteger reaches 0, I'd wait a short amount of time and recheck that it's still 0 to make sure it wasn't just transitioning activities.
Create an Application class and include in the manifest
<application
android:name="com.example.hello.MyApplication"
public class MyApplication extends Application implements
ActivityLifecycleCallbacks, ComponentCallbacks2
override the following method
#Override
public void onTrimMemory(int level) {
// this method is called when the app goes in background.
// you can perform your logout service here
super.onTrimMemory(level);
}
this is valid of API level 14 and above.
You can even perform the the logout based on the amount of time the app is in background, which i would suggest is a better option. here is what you can do to create as "session timeout"
save the time stamp in SharedPreferences inside the onTrimMemory(int level) method
on all your activities onStrat() get the time stamp from sharedPref and compare it with current time. based on this you can perform a logout.
and clear the shared pref on onCreat of MyApplication