On Android, I'm trying to catch the event where my app comes back to the foreground from the background. In other words, the app was active, then the user minimized it (by clicking the home button or starting another app or something), and then the user runs the app again.
I can add the onRestart() method to an activity as follows:
#Override
public void onRestart() {
super.onRestart();
Log.d("MAIN", "onRestart called.");
}
But this only works when that specific activity is the active one when the user minimizes the app.
Is there a way to catch this for the whole app somehow? Or do I need to add onRestart to every single activity I have? (I suppose I could create a superclass on which all the other activities are based).
Thanks!
Is there a way to catch this for the whole app somehow?
No, because there is no concept of an app "restarting".
Or do I need to add onRestart to every single activity I have?
Presumably. Or, find a way to avoid needing to "catch the event where [your] app comes back to the foreground from the background".
I think the method you need is void onResume()
here is there android developers page for activities , check the "Implementing the lifecycle callbacks" part of the page .
http://developer.android.com/guide/components/activities.html
hope this helps.
Related
Just like in visual studio WinForms. I first close any connections before exiting the application. Otherwise, the application will still run in the background. I do this by clicking on the form itself and then click on the closeBeforeexiting property.
I then close all of my connection just before the application exits.
My question is then, how do I do this in an android studio? I want to close of a RFID class first before exiting the app. The reason for this is another app on the device that uses the same RFID class. But since the RFID class did not close safely and is still running in the background, the other application crashes because it cannot access this class.
Is there a closeBeforeexit property in android studio, perhaps in the res->layout->content_main.xml that provides me with the same functionality as in visual studio
I could do this using an exit button on the application but I see people generally use the back button that is already on the screen to exit the application. Is there any way I can access this back button and put my close connection function in there?
Answer:
#Override
public void onBackPressed()
{
try {
RFIDReader reader = RFID.open();
reader.stop();
reader.close();
super.onBackPressed();
return;
}
catch (ReaderException e) {
Toast.makeText(this, "Error: " + e, Toast.LENGTH_LONG).show();
}
}
Yes, you can intercept the back button and do anything you want there (even cancel the back navigation), but then you'll miss the cases where the user leaves by the Home button, or an incoming call, or through a notification...
What you should do instead is to override the onPause, onStop, and/or, onDestroy methods for your activity. They are all callbacks related to the activity life cycle, which you will soon need to learn about.
In short: onPause happens when you lose focus, onStop when you're no longer visible, and onDestroy when the activity is fully deleted (e.g. the user pressed "back", but usually not when they pressed "home").
In your case, onStop is probably the most suitable one.
My question is then, how do I do this in an android studio? I want to
close of a RFID class first before exiting the app. The reason for
this is another app on the device that uses the same RFID class. But
since the RFID class did not close safely and is still running in the
background, the other application crashes because it cannot access
this class.
You better read -> Understand the Activity Lifecycle to see how Android works with Activities and background tasks. If you're running the task in a background task, you should be able to close the RFID using close() method.
I could do this using an exit button on the application but I see
people generally use the back button that is already on the screen to
exit the application. Is there any way I can access this back button
and put my close conection funstion in there?
Using onBackPressed() method should help in your case. Keep in mind that finish() method is not a good approach to close the Activity.
Is there a closeBeforeexit property in android studio, perhaps in the
res->layout->content_main.xml that provides me with the same
functionality as in visual studio
layout->content_main.xml is the UI layout in Android and to be able to handle such things, you'll need to go with java or Kotlin.
Let's say a user is using my Android app, I have a DialogFragment YourTanks
(it shows the various tanks you own!)
public class YourTanks extends DialogFragment implements View.OnClickListener
So again, the user is literally looking at that "page", seeing their tanks and so on.
They get a phone call or decide to use another app, perhaps their calendar, email, whatever.
Note that, of course, my app does not quit, it's still running in the background.
They finish with the other app. On the home screen or app screen of the Android, they click the icon of my app. Now, my app appears again and once again they can see their colourful tanks, etc.
So - I want to know that they have opened the app, I want YourTanks to be alert to that.
#Override
public void onStart ()
{
super.onStart();
Utils.Log("WE ARE IN onStart !!========");
Utils.Log("I think this means the user just 'opened' or 'reopened' the app.");
Utils.Log("Better ask on SO though.");
}
Indeed, is this the best way to do what I describe, or, do you have to do something at (perhaps/) the activity level, or some other concept?
(Note that on iPhone, for instance, you more or less use something like -(void)applicationDidBecomeActive:(UIApplication *)application in the overall application singleton.)
you need onResume instead, the activity could just be paused when the app is re-opened,
This function is also called after onCreate.
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Here is the documentation how it's all called and working.
I'm designing a news app where I need to download fresh articles and their detailed stories whenever user opens my app. I'm doing all of this a background thread. My prime focus was that the background thread should stop as soon as user exits the app so as to prevent user for incurring extra download charges.
To achieve this, I initiate background download in my splash screen and I keep on checking for flag variable that lets the background process know if the app is still running.
Now my question is: I'm very clear about initialization of this flag variable. I've initialized it in onCreate() of Application subclass since it is the point where application starts. But I've no idea where to clear it. I tried doing it in onDestroy() of my MainActivity. However, I found that onDestroy() is often called on transition between one activity to another if system needs to free memory. So, doing so there would stop my background thread even when I'm switching across screens and not actually closing the app. How should I deal with this scenario ? Is there a smarter way of handling this ?
I don't think you have to do that : either the user is pressing the "Home" button (which most people do) and then it's common for apps to keep running in background, and as so to still be easily accessible to the user in the state they left it. Either you provide a "close app" button which really kills the app, which will also kill every kind of thread created by the app and you don't have to worry.
If you really want, you could capture the "Home" clicks, and use those to kill the app before returning to home, which is a nice thing to do if your app has 0 initialization time.
But I've no idea where to clear it. I tried doing it in onDestroy() of my MainActivity.
In order to know if the activity is destroyed because the user finished it (with Back) or Android will re-create it, you could use isFinishing();
Something like:
protected void onDestroy() {
super.onDestroy();
if(isFinishing()) {
// stop the news feed download
}
}
Or better, stop the feed download in finish():
public void finish() {
// stop the news feed download
super.finish();
}
To go back to what you said above with:
I'm very clear about initialization of this flag variable. I've initialized it in onCreate() of Application subclass since it is the point where application starts.
Even if the activity is finished, the application is very probable to still live. The Android OS will decide when to kill it. So you will initialize the download once the app starts, then you will stop it on onDestroy() or on finish() within Activity, depending on your desire, but if the application doesn't stop (most probable) and you're re-entering again in the news activity you should be starting the news download.
I would rather initiate the download in the background in onCreate(Bundle savedInstance), but when savedInstance is null (so I know this is the first create of this activity) and stop it (if hasn't stopped already by itself) in finish();
Hope it helps!
To begin with for downloading datas from webservice (json or xml) you should use AsyncTask (easy to use)
so what i mean was, to clear your flag with ondestroy(), for when the application is exited, and maybe you can catch when the home button is pressed
Override the below method in your Activity,
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
And now handle the key event like this,
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
//do something
}
if(keyCode==KeyEvent.KEYCODE_BACK)
{
//do something
finish();
}
return false;
}
How to stop application from running in background in android?
I want my application to start fresh everytime it loads. How to do it programatically.
Override onStop method of your activity:
#Override
public void onStop(){
super.onStop();
finish();
}
But I think it's a bad idea to restart your app each time. It's better to override onStart method, and handle "restart" here.
Actually, your app doesn't "run" in background. Android OS keeps it in memory, or saves state of your activity to device (and then you can load it, using savedInstanceState param in onCreate method).
You can use onResume event to reload again, or look here.
EDIT:
Actually you need to use these functions to reload your application when user navigate it.
After adding finish();
This code will completely stop the application.
System.runFinalizersOnExit(true);
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
The whole Android ecosystem is based on the fact that the user shouldn't have to worry about "terminating" or "starting from scratch" an application. If you need to start your application from scratch every time, that's probably because you have tasks in your "scratch" that shouldn;t be there, and should probably be somewhere in onResume.
Please give us more details if you want a more detailed answer.
you should make use of Intent.FLAG_ACTIVITY_CLEAR_TOP to finish all other activities running in activity pool and call the first activity where you can ask to exit from app
I have an application which I would like to be fully disabled/closed when it is paused (IE. When the user presses the Home, End (call) and Back button I would like the application to be closed, instead of being saved in the history stack).
How do I do this....?
Thanks.
Implement onPause() in your activity and call finish() on your activity. Bear in mind, though, that this will occur on every pause, including dialogs, incoming calls, users activating a Notification. You might want to consider doing finish() in onStop(), which would at least solve the dialog problem.
Also, bear in mind that users will may get confused when using your app, thinking it has crashed since it is gone when they try to get back to it.
you can easily do that by setting true the "noHistory" attribute in to your activity element, in the manifest
http://developer.android.com/guide/topics/manifest/activity-element.html#nohist
You know how you have an OnCreate() method in your activity which performs actions when you start. You need to add something like:
#Override
protected void onPause(){
finish();
super.onPause();
}
in your activity to add actions before it starts
in this case the
finish();
command is what you want to execute before your activity pauses.