android log out help - android

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

Related

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
}

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.

android is it possible to know time application spend in bg

any android application consists of many activities, only one activity can be in foreground.
so I want to know for a specific application how many times it takes while it is in the background.
I mean this
application starts -> application go to foreground -> user plays in the application -> application goes to bg (here I want to save the time) -> application goes to foreground (here I want to save the time)
by minusing the two times I could know what is the time which the application spends in the background, but that is a very hard work, because I have to edit the on pause and on resumes for all the activities, I have more than 200 activity.
hypothenticlly
I think the mainfest had something to deal with my problem but I couldn't find it.
One solution would be to create your own activity class (class that extends Activity) and use that as a base for all your activities. In your own activity you can keep code that all activities share.
You would still have to edit all you activities to extend this new class, but it is much easier to add things like this.
Write one super activity for all your 200 activities and extend super activity for every activity. Handle the time measurement in Superactivity of onpause() and onresume() methods.
Example :
Parent activity:
class ParentActivity extends Activity
{
// here in onResume and onPause methods handle your time measurment things...
}
ChildAcitivity:
class ChildActivity extends ParentActivity
{
#override
public void onPause()
{
super.onPause();
}
#override
public void onResume()
{
super.onResume();
}
}

Android Application, Activities, and UI Thread

I'm working on an Android project that consists of several different Activities all associated with the same Application. We have some common tasks coded in the Application so that we don't have to duplicate them, and one of these tasks is regularly verifying a TCP connection to a dedicated server -- a heartbeat, I suppose.
If it's detected that the connection to the server is lost, I need to notify the user and I'd like to do this in a way that doesn't require me to check all the possible activities to see which is currently "on top".
Is there a way to call runOnUiThread() on whatever activity may be on the UI thread without knowing it explicitly??
Thanks,
R.
Regularly verifying a TCP connection
Sounds like this should be implemented using a service..
If the alert is very simple, and has minimal importance, I would suggest using a Toast.
If the alert is crucial, but it doesn't require the user's immediate attention, use a Notification.
If the alert demands immediate user attention, you should use a Dialog. You won't be able to start a dialog directly from a service or broadcast receiver because they don't have a window associated with them, but you can use an intent to start an activity on a new task. You can style the activity to be whatever you want. It could even look like a dialog box (or show a dialog box when it's started). Starting the activity in a new task will make sure the user can navigate back to whatever they're doing.
You can notify your Activities by sending Intent and registering BroadcastReceiver in each Activity you want to be notified.
service or application can be your context:
Intent i = new Intent("MY_ACTION_FROM_SERVICE_STRING");
context.sendBroadcast(i);
activity:
public class MyActivity extends Activity {
private ActivityBroadcastReceiver recvr;
public void onReceiveCommand() {
//do something
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
recvr = new ActivityBroadcastReceiver(this);
this.registerReceiver(recvr,
new IntentFilter("MY_ACTION_FROM_SERVICE_STRING"));
}
}
receiver:
public class ActivityBroadcastReceiver extends BroadcastReceiver {
private MyActivity target;
public ActivityBroadcastReceiver(MyActivity target) {
this.target = target;
}
#Override
public void onReceive(Context context, Intent intent) {
target.onReceiveCommand();
}
}
One of the simple way (which I've adopted for my project too) is to create a base Activity class (preferably Abstracted) and then make your normal activity classes to extend it. By this, you may put a general piece of code in the abstracted class which may help you to detect currently visible activity.
Moreover, you may set a BroadcastReceiver in your base activity class which will always be ready to listen broadcasts regardless of setting it individually in your child activities and then set it to listen for broadcasts sent from your tcp thinggy.
Do not do any trickery. Implement Observer pattern, so any activity would register its listener in onResume() and unregister in onPause() and whatever will happend your Application object code needs just to tell about that to registered listeners, no matter what Activity they are in

Categories

Resources