Android do something when activity is shown - android

Original question:
A button in my app starts an activity, which needs some time to prepare classes.
To let a user know this, I start a new loading activity that starts the actual activity.
This activity needs to be shown before the actual is started.
But all methods of the Android lifecycle seem to be called before the activity is shown to the user and if I start a new activity before the activity I'm currently in is shown, it won't be shown anymore.
I tried:
Starting the activity in another thread, but this does not work because the startActivity(...) seems to block the UI reload
Waiting a few milliseconds before starting the activity, but this seems dirty
Any help is appreciated! Please tell me if using a forward activity is not the right solution!

Answer for people who are searching:
Use this code to do something when the activity is already visible:
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
// do something
}
}
If the activity can also turn visible shortly after your code, use Androids lifecycle methods (here probably onResume()):
#Override
protected void onResume() {
super.onResume();
// do something
}

Related

What is the default implementation of onBackPressed() in Activity

I want to know the default implementation of onBackPressed() in Activity. How to deal with the Activity recover in the default implementation of onBackPressed()?.
The following is the issues I suffer from. I have a test Activity code like this:
public class MainActivity extends Activity {
public static boolean test = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this,"is "+test,Toast.LENGTH_LONG).show();
test = !test;
}
}
When I first enter the app, I get 'is false'. Then I click back button and get to the home screen. After that, when I enter the app, I get the Toast 'is true'. I think the onBackPressed() should kill my app when it gets back to the home screen, but It does not. This is my question.
If I override onBackPressed() like this
#Override
public void onBackPressed() {
// super.onBackPressed();
finish();
try {
android.os.Process.killProcess(android.os.Process.myPid());
} catch (Exception e) {
e.printStackTrace();
}
}
I always get the Toast 'is false' after I enter the app.
Can anyone explain this problem and tell me what the default implementation of onBackPressed()?
I'd like to know the flow process in onBackPressed() in detail. I have read some of the source code on onBackPressed(), but I couldn't understand it well.
Thanks in advance.
The default implementation of Activity's onBackPressed() probably won't tell you a lot about the actual Activity/application lifetime. You should dig much dipper to understand the internal Android (and Linux) "mechanics" on application/process killing.
What an application developer should know is that once an Activity is in background (Home button pressed, incoming call received etc., i.e. onPause() followed by onStop() have been invoked) its process may (similar to what you did with android.os.Process.killProcess(...)) or may NOT be killed. See Multitasking the Android Way by Dianne Hackborn for the reference.
As to finishing an Activity by pressing the back button, it does not mean its instance will be immediately killed and the memory garbage collected (see this answer). It just means a new instance of the Activity will be created next time you navigate back to it.
Regarding your code and the statement that
When I first enter the app, I get 'is false'. Then I click back button and get to the home screen. After that, when I enter the app, I get the Toast 'is true'. I think the onBackPressed() should kill my app when it gets back to the home screen, but It does not.
This is the case when the system didn't kill the process while the Activity were in background (again, it is not guaranteed). If it did, the Toast would have shown false.
In order to check that a new instance of MainActivity is created each time you press the back button and then navigate back to the app, I don't recommend to use a static variable, - it appears to be not that obvious (see, for instance, is it possible for Android VM to garbage collect static variables... or Are static fields open for garbage collection?).
Besides you're simply switching between true and false that might be confusing. Instead of using a static variable you might use a non-static one incrementing it, for example, or toast the hash code of the current Activity instance, like Toast.makeText(this,"is " + this.hashCode(), Toast.LENGTH_LONG).show(). By doing this the Activity lifecycle should act as per the documentation.
If I override onBackPressed() ... I always get the Toast 'is false' after I enter the app.
This is more or less similar to what if the system kills your app's process.
From the AOSP Activity class found here:
/**
* Called when the activity has detected the user's press of the back
* key. The default implementation simply finishes the current activity,
* but you can override this to do whatever you want.
*/
public void onBackPressed() {
if (mActionBar != null && mActionBar.collapseActionView()) {
return;
}
if (!mFragments.getFragmentManager().popBackStackImmediate()) {
finishAfterTransition();
}
}
So basically when you call finish, the process is not actually destroyed. You can read more about that here. This means that the memory in your app isn't destroyed, so when you restart your app, the boolean value from before is remembered.
In the case of your overridden implementation, you are explicitly destroying the process, which will clear memory of your activity state, so when you restart the app, the boolean initialization will occur again.

Running code in onPause() or onStop() state of the activity

There is a function in my android app that needs to run every time the user tries to edit his or her profile. There are two parts of edit profile in my app (please don't ask why, it has a very long tedious reason behind it). I need to revert back the changes the user did in the first part of the edit profile if the user decides to cancel everything. I have made a cancel button in the part two of edit profile but my question is, what if user presses the return button or the home button on the device and the app calls the onPause() and on onStop()? how can I run the same code in these two phases of the activities? Anyone out there who knows how to put code in different states on activities? Do I just make a function onPause() and stick the code in there? Would that work?
Yes, it should definitely work. In your case, you should write your code in onPause() method.
Here is a summary of the Activity Lifecycle:
onCreate():
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
Always followed by onStart().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Write your code here
}
onStart():
Called when the activity is becoming visible to the user.
Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
#Override
public void onStart() {
super.onStart();
//Write your code here
}
onResume():
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
Always followed by onPause().
#Override
public void onResume() {
super.onResume();
//Write your code here
}
onPause():
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.
#Override
public void onPause() {
super.onPause();
//Write your code here
}
onStop():
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.
Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
#Override
public void onStop() {
super.onStop();
//Write your code here
}
onDestroy():
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.
#Override
public void onDestroy() {
super.onDestroy();
//Write your code here
}
You can do many things inside both onPause and onStop, just remember to call super.onPause();, super.onStop(); or whatever you need inside each one, just follow the pattern below. Simply add the code to your Activity and you're good to go.
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// Do what you want.
}
Additionaly, if you want your users to be able to go back on your activity and edit something instead of closing it, you can just call onBackPressed():
#Override
public void onBackPressed() {
super.onBackPressed();
// You can just call onStop to close the app
// or do what you want.
}
Only onPause is guaranteed to be called

How to disable or override the oncreate method in Android

I have 3 pages in my application. Page A,B,C. When i click next button in A page the page will navigate to B page. In that page there will be some request and response process and Progress indicator will happen. Then when i click next the page will navigate to C page. There also some request and response process and Progress indicator process will happen. Now my problem is when i click back button from page C The page is navigate to B page. But the request response process and progress indicator process is working. Here i don't want do this process when i click back button. Now i have try like this:-
#Override
protected void onStart() {
super.onStart();
Log.v(this.getClass().toString(),"onStart");
}
Here the request and response process is not working when i click back button. But the progress indicator is loading. This progress indicator is continuously rolling. How to disable all the functions. I just want to go back. Do not do any other work. Please help me to solve this issue. Sorry For the poor English..
As you can see, you add a flag Intent.FLAG_ACTIVITY_CLEAR_TOP. This flag will clear all previous activities.
Intent.FLAG_ACTIVITY_CLEAR_TOP - If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
And also you finish the current activity, so navigating back to page B call B's onCreate method where you have those requests and process stuff. Avoid adding flag and finish() methods.
You don't want to override the onCreate() method for this usecase, why would you do that? The activity is created, and the process will run. What you want is to override the onBackPressed() method, so that you cannot exit the Activity until the process is complete.
Similarly to these: Android: Proper Way to use onBackPressed() with Toast but here you want to make a boolean that is set to false while the process is not complete, and set to true when it's done. Allow onBackPressed() to call super.onBackPressed() only when the boolean is true.
#Override
public void onBackPressed()
{
if(processesCompleted == true)
{
super.onBackPressed();
}
}
You can't disable the onCreate() method in android but you can however override it like you do with the onStart().
I suggest you take a look at the life cycles of either fragments or activities, depending on which you use.
Fragments:
http://developer.android.com/guide/components/fragments.html
Activities:
http://developer.android.com/reference/android/app/Activity.html
It is hard to understand what the problem really is without more code, but basically the code in onCreate will mostly not be called when you press the backbutton since an activity will be paused until the phone needs more resources and then destroys it. If an activity is destroyed the onCreate method will be called and there is nothing you can do to change that.
If my answer dosen't help, please provide more example code.
If all your cards have different activities, the backbutton should work perfectly. However if your activity is brought to the front, nothing will be reloaded, except the onresume. In the onresume you can perform a new loading structure or something you want to achieve.
When you don't have different activities, use the override at onBackPressed(), that will handle the backbutton.
But place some code for a better answer
You can create a new function in which you run the processes and call
it on onCreate and use a Boolean flag to make sure when you go back to
that activity and flag is checked the function is not called. Then
save the value of flag in savedPreference onPause() method and you are
done and onCreate() method load your saved preference.
Something like this
boolean flag = false;
#Override
public void onResume()
{
super.onResume();
// load savedPreferences
}
#Override
public void onPause()
{
super.onPause();
//save savedPreferences
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(flag == false)
{
//function call
processes();
}
}
private void processes()
{
flag = true;
// do stuff here
}

Android onResume from Application

My client wants their app to always show a "WARNING" screen when the application starts or when it awakens from sleep. I've tried creating an onResume() event in my master activity (which every other activity inherits from), but this causes an endless loop:
Activity is called, onResume() is fired
Warning screen fires, causing the calling activity to be paused
User clicks OK to accept the message, returning the user to the prior screen
Activity is woken up
Go to 1
Even if I could get around the endless loop, the Warning screen would fire whenever a new activity loads. This is what I like to call a Bad Thing.
Is there a way to mimic the onResume() event but at the application level rather than at the activity level, so that I can avoid these scenarios but still have the warning pop up on application wake?
Why not just use SharedPreferences.
http://android-er.blogspot.com/2011/01/example-of-using-sharedpreferencesedito.html
Store the time the popup is brought up, and if it was within 5 mins, or something, then don't pop it up.
This will break your loop and not completely annoy the user.
I would write a method to pop the warning and, in onPause, set a global flag. Check that global flag in the onResume, then reset it in your popup method. Simplified pseudo code...
class myApplication Extends Application{
boolean appIsPaused = false;
}
class myActivity Extends Activity{
#Override
protected void onPause(){
appIsPaused = true;
}
#Override
protected void onPause(){
if (appIsPaused){
showPopup();
}
}
public void showPopUp{
if (!appIsPaused){
return;
}
appIsPaused = false;
}
}
You could use an AlertDialog to show the warning message, it would solve your problem.
Else, try to start the warning screen from the onStart or onRestart of your application ?
Here's the android lifecycle if it can help : http://developer.android.com/reference/android/app/Activity.html

Finishing the current activity after the user clicks on notitifcation

In my android client program, when ever the user has updates a notification is received. When the user clicks on the notification, he is taken to a new activity where the notifications are displayed. Now the problem is while the user is viewing the updates if another notification is received and if he clicks on that notification a new activity is not being created. The previous activity is displayed. the activity is not getting refreshed.<
I suspect this is because the current activity is not finished. How should I overcome this?
Why dont you try onWindowFocusChanged (boolean hasFocus) in your code. What is happening in your case is the Activity Window is already in focussed state So nothing will happen when you click the notification bar and move to the same activity window.
onWindowFocusChanged (boolean hasFocus) will get executed each time you enter into that activity. So put your entire code into this. Even when the activity is called for first time,It will get executed. So copy ur code from public void onCreate(Bundle savedInstanceState) to
public void onWindowFocusChanged (boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
setContentView(R.layout.layout_name);
//Your code to be executed here
}
And yea you need to have Oncreate() function also so you declare that as
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
Try this. I hope it works for you
put this in the activity code in your manifest (can play with the parameter to fit better to your app).
android:launchMode="singleTop"
Try to add this attribute on your activity tag on the manifest :
android:launchMode=["multiple" | "singleTop" |
"singleTask" | "singleInstance"]
with value singleTop, it will not create an other activity but call the onNewIntent method of a potential Activity if exists.
Activity Element Documentation
Instead of finishing the current activity why should you use the onResume() method to update the ui with new notification data. Write the method to update the ui components and call it from onResume().

Categories

Resources