Create a Button to Close the Program - android

My project has 4 activities and users from activity A go to B after that to C and D. I need to create a button in activity D to close program directly because if user has to close all activities ( D ->C -> B -> A-> close) it would be unfriendly.

Register a broadcast receiver in each of the activities, listening for the "close all action", when the button in the last activity is pressed, send that broadcast, so all the activities register will execute their "onReceive" method on the broadcastreceiver, and there all them will be finished as long as they are registered.
This will definitely do the trick, although to be honest is quiet a poor implementation, chances that you are doing something wrong in the navigation are high, maybe fragments or a tab would be better suited for what you are trying, in stead of creating such a stack of activities...
Hope this helps...
Regards!

I think onActivityResult could be the better option.You could finish the activity if required task is being completed otherwise just backtrack on previous activity

You should override onBackPressed() from each Activity and call finish().

Assume the first activity in your application is named ActivityMain. Presumably it will be the oldest one on the stack.
Create an intent to start ActivityMain using the flag FLAG_ACTIVITY_CLEAR_TOP. Set an extra in that intent to indicate this is an application exit, and call startActivity() with that intent. This will clear the stack and get you back to Activity main.
In ActivityMain call getIntent() then check for the exiting application Extra value. If it is set, call finish().

A not so elegant solution:
Instead of calling startActivity, call startActivityForResult, from A to D.
On Activity D, when your button is pressed, set any result (let's say Activity.RESULT_OK) and call finish().
On each Activity (from A to C), override the method onActivityResult to check for the result. If the result is Activity.RESULT_OK, then you set the same result and call finish() again.
If you want, instead of just setting the result, add an Intent with some flag to tell the previous Activities to finish themselves.

Simply do one thing . In your activities add an overriden method onPause
onPause(){
finish();
}
This will close all your activities once you press back from any activity.

Related

How will I permanently exit my Android app using onBackPressed from my last Activity

I have 8 Activities in my Android app and I want:
1)Every time I press Back button during my first 7 Activities to go back to my previous Activity(Act1< Act2< Act3< Act4< Act5< Act6< Act7) BUT
2)ONLY when I am in the 8th Activity I want to definitely exit my Android app and go to my phone's Home Screen.I try to do it by overriding onBackPressed method in my 8th Activity (Phone Home Screen<-Act8)
I found an Android implementation in which I insert finish();in every intent of all my 8 Activities but this is not what I want since this way I can't go back to the previous Activity whenever I want(with finish(); every current Activity is removed from back stack).
How will I do it please?
My code so far in my 8th Activity is:
#Override
public void onBackPressed()
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
Another way: create a 9th Activity and call it FinishAllActivity or something like that. Make this activity call finish() and then return in its onCreate().
In onBackPressed() in Activity 8, start FinishAllActivity using the FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK flags (see this question for more details). Activities 1-8 will be removed from the stack, then the 9th Activity will start and immediately terminate and your task stack is clear. When you reopen the app it should start from Activity 1.
The advantage of doing it this way is that you don't have to modify Activities 1-7.
Add a public static boolean to one of your classes that indicates the app is exiting. Set this boolean in activity 8 when you want the app to finish, and have all of your other activities check it in their onResume() and finish immediately if it is true. Make sure the first activity clears it before finishing, or it may still be set the next time the app runs. (Android doesn't necessarily discard the VM when your last activity finishes, so the class and its static members may be reused next time.)
Note that this is the simple way, not the "Android way." Global variables are generally frowned upon, for reasons you can Google. The "correct" way to do this would be to start each activity for result and return a result to onActivityResult(...) that indicates whether the app is exiting.
You can implement a broadcast receiver and have each of your Activities that you want to close call finish() when they receive the broadcast (which will be sent from your last activity). I would imagine you'd need to have your broadcast receiver class be either an anonymous inner class or a private class within your activity(s) so that you can easily access your enclosing Activity's finish method.
Here's a good example of broadcast receivers:
http://www.tutorialspoint.com/android/android_broadcast_receivers.htm
Look at the custom intents section.
Doing it this way is a loosely coupled way to implement what you are looking to do.
use FLAG_ACTIVITY_CLEAR_TOP Flag in your intent like below example.
Intent intent = new Intent(getApplicationContext(),FirstActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
in your first activity check below condition.
if (getIntent().getBooleanExtra("EXIT", false)) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
}
here FLAG_ACTIVITY_CLEAR_TOP work like below example
consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.
so here you have to call D is your last activity and A is your first activity.
This way you are finishing your 8th Activity returning to your 7th Activity and same time you are like emulating a pressing of Home button on a device. When you rerun your app it will appear with 7th Activity on a screen. If you wish to see the 8th Activity in this case then just remove the finish() method. If you wish next time your app to start with 1st Activity then you should finish all the activities from 8 to 2nd but not the 1st. Also you could launch your 1st Activity adding a FLAG NEW_TASK or some other flags.
UPDATE
My advise (for the quick result without changing the workflow) is to use startActivityForResult() to start all activities in chain. When user exits the app just return a special parameter using setActivityResult() to get all nested activities know about user's choice making all nested Activities to run finish(). This way all your 8 activities will be finished properly.

onCreate called despite using FLAG_ACTIVITY_REORDER_TO_FRONT

I have 2 activities (A and B) and they have 2 buttons to switch between.
A oncreate
B oncreate
A oncreate
A onresume
what I wanted to do is after sending intent from B to A oncreate should not be called but at this point it does. To overcome that I found FLAG_ACTIVITY_REORDER_TO_FRONT (from here) and thought it could called only onresume but it didn't.
FLAG_ACTIVITY_REORDER_TO_FRONT does exactly what you think it should do. However, if you start ActivityA and then ActivityA starts ActivityB and calls finish() on itself, then when ActivityB starts ActivityA with an Intent that has FLAG_ACTIVITY_REORDER_TO_FRONT there will be no instance of ActivityA to bring to the front. In this case Android will simply create a new one. I can only assume that is what you are seeing.
FLAG_ACTIVITY_REORDER_TO_FRONT changes activity history. If the requested activity is found in the history of previously visited activities (in a task), the older history record for this activity is cleared. So, while pressing back button, user will not encounter this activity in a task.
This flag won't affect the call to onCreate(), If activity does not exists in the task (not loaded or destroyed), onCreate() will be called to create it.
You can't just cancel onCreate. If B is full screen activity android can kill A activity and will recreate it when you try to restart it with FLAG_ACTIVITY_REORDER_TO_FRONT flag and call it's onCreate method. If Activity A will be still alive at the monent when you try to bring it to front, onCreate method should not be called.
Maybe in your case you should try to use fragments?

Android how to create activity only if it wasn't created yet

I have a problem cause when I go to different activities using startActivity function,
they always get created from scratch. Even if activity A was visited before, when I go to activity B and then A again, activity A is created again.
The problem is with back button, cause if I go to Activity A then B then A and then B,
in order to close the application I have to press back button 4 times.
I guess that it shouldn't act like it and user should be able to go to activity A when first pressed back button and the second press should close the application.
How to solve this issue?
Greetings
If you have activity transitions like:
Activity A -> Activity B
Activity B -> Activity A
and you want the user to go back to the same instance of Activity A in this case, maybe you just need to call finish() in Activity B after you call startActivity() for Activity A?
If this isn't helpful, please give us more information about what you are trying to do.
make sure you implement onSaveInstanceState and be prepared to restore your activity from a Bundle in onCreate. that's how you re-establish where you were when you return to an activity.
add launcheMode="singleTask" to your activity in the manifest
You need to set FLAG_ACTIVITY_SINGLE_TOP to your intent for launching activity A. Doing so will cause your previously created activity to re-use. Make sure you do handle your afterwards intents in onNewIntent method. For more info.
You need to set the flag FLAG_ACTIVITY_REORDER_TO_FRONT when you start activity A from B or vice versa, like
i = new Intent("....ActivityAorB");
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
I've tried solutions proposed so far, however they didn't do it for me.
What did however, is using flag FLAG_ACTIVITY_CLEAR_TOP while starting activities.
Thanks for pointing me in the right direction though.

Run Activity B from Notification and force back button to run Activity A

I have an Android application that contains two Activities.
Activity A has a button that launches Activity B using Context.startActivity(Intent intent).
There is also a Notification that opens Activity in the same way.
If I start B from this notification and press back button - it just closes B and does not shows A like I go there with normal case.
Is it possible to force B to bo back to A if started from notification without history stack ?
Solution
As stefan and Paul Lammertsma mentioned, the best way is to start A from notification and in A create new intent with B - but not in onCreate() !
I dig this a bit and found that if I set in AndroidManifest a new property for A activity:
android:launchMode="singleTask"
there will be in A activity called
onNewIntent(Intent intent)
And there we should checl if Intent containst extra value passed from notification - and if so, then we call new B intent.
Thank you both and good luck with it for next devs ;-)
I would suggest having the notification call Activity A (instead of B directly) with some flag in its extras bundle. In A's onCreate(), check for the flag, and immediately launch Activity B. This will ensure that pressing back on B will return to A.
An easy way to achieve this would be to actually start Activity A from your Notification with a flag to call Activity B instantly.
So you just have to put an extra to your intent you are starting in your Notification and you have to check in Activity A if this extra exists and if it exists then you start Activity B.
Update: another way, but in my opinion not so good, would be to override the onPause() method of your Activity B and call Activity A there.
Maybe not the prettiest solution, but nevertheless a quick one;
add a boolean extra to the intent launching B, "launchedFromNotification" or something like that.
In activity Bs onCreate() you store that boolean value for later use.
In activity Bs onBackPressed() you can check the value of your boolean and if true, launch activity A before calling finish();
A prettier solution may be to launch activity A from the notification, with an extra telling it to directly launch activity B.

Update the first screen automatically even if it is declared as android:launchMode="singleTask"

I have 2 activities. Activity A and Activity B. Both calling each other though intent. Activity A calls Activity B. Activity B accesses database and sends it back to activity A through putExtra() and getExtra().
Now my activity A is in declared like this android:launchMode="singleTask"
When I go back to activity A I want my this activity A to be updated or refreshed automatically. But to my wonder what I understood on debugging that if I declare an activity as launchMode="singleTask" then it just brings forth the screen to top from the stack. It does not actually go inside the code.
Is the concept what I understood correct ?
The solution I see is have a refresh button and on click of that access the code and update screen. But I do not want to do that. Do you think there is any other alternative ? I do not want to change launchMode="singleTask"
Thanks in Advance.
Try startActivityForResult(intent); and while you have finished in B setResult(RESULT_OK); and finish(); the B activity, and in A onActivityResult(int,int,intent); catch the result code if it is RESULT_OK update your A.
No matter which launchMode, when you switch from Activity B to Activity A, the onResume() method must be invoked. You can put your refresh code there to get your activity A updated.
put your refresh part in the onResume method .Once Activity B completed your onResume method will be invoked in Activity A.

Categories

Resources