Android exit whole program syntax - java

currently I'm working on Android development, now I'm facing a problem to exit the whole application that had launched.
I'v tried .finish(), but it doesn't show what I want.
I have 2 Activities, A and B. Activity A will forward to Activity B when button click. In activity B, when I click button "Exit" (that I created) with the listener to trigger .finish(), it just back to Activity A but not to close whole application (what I want is back to home screen directly and kill the background process as well).
How can I exit whole application wherever in the application? Thank you.
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//here to exit whole application not just backwards to previous activity
}
});

You write in Activity A after
startActivity(new Intent(A.this, B.class))
finish()
then you also write in Activity B finish() on button click listener. It should works.
public class A extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(A.this, B.class));
finish(); // you must write this also in A activity to close whole application
}
});
}
public class B extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_1);
Button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}

EDIT: I assumed there are cases when the underlying activity either should or shouldn't be terminated on return. This will allow you to handle both cases.
Case A)
Activity A starts activity B, which starts activity C. You want to close all of them from activity C. If they're all in the same task (i.e. probably your case) you can close the whole task by calling
finishAffinity();
According to docs this is what happens:
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
See Activity.finishAffinity().
Case B)
Activity A starts activity B, which starts activity C. You want to close activities B and C from activity C.
This is how you start activity C from B expecting and handling a result:
public class ActivityB extends Activity {
private static final int RC_ACTIVITY_C = 1;
public static final int RESULT_FINISH = 1;
...
public void startActivityC() {
Intent intent = new Intent(this, ActivityC.class);
startActivityForResult(intent, RC_ACTIVITY_C);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_ACTIVITY_C && resultCode == RESULT_FINISH) {
finish();
}
}
}
This is how you let activity B it has to finish from activity C. At any point before finishing activity C call:
setResult(ActivityB.RESULT_FINISH);
See Activity.startActivityForResult(Intent, int) and Activity.setResult(int).

You can try System.exit(0). That should do the job.
EDIT: Take a look at this post for the difference between finish() and System.exit(). Difference between finish() and System.exit(0)

Related

Retaining variable value when stopping android activity

I've got two activities, A and B. Activity B can be opened by pressing a button in Activity A.
In activity B I have an integer variable which I would like to keep for when I return to activity B from A. My problem is when I press the back button to go from B to A the activity is destroyed.
I have overwritten the onBackPressed method to:
#Override
public void onBackPressed(){
Intent i = new Intent(this, Game.class);
startActivity(i);
}
I can see from my logs that activity B is in the state onStop() after back button is pressed, however, onRestart() is not being called so the activity must be getting killed for memory reasons.
I have read answers to other posts suggesting I use onSaveInstanceState() but when I try to access the bundle in onCreate() the bundle is null. Method onRestoreInstanceState() does not get called.
protected void onSaveInstanceState(Bundle savedInstanceState){
Log.i(LOG, "instance saving");
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("score", userScore);
}
I have also tried SharedPreferences but this is not useful because I do not want my data to persist when the activity/application is intentionally destroyed.
I think your problem is in understanding the whole Task ecosystem. When you press back button you pop out your activity from the Task, because of that it is destroyed and onDestroyed() is called. To sum-up I think you are just getting every time a brand new activity. onSaveInstanceState() isn't called because activity is killed by user, not by the OS.
Take a deeper look at this developer tutorial.
Also I think those two must be helpful : me and me!
you can store variables in the app class https://developer.android.com/reference/android/app/Application.html or you can make your own singleton class for this
https://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
Starting a Activity - A on onBackPressed will definitely kill the current Activity - B. Instead of starting Activity again just call onBackPressed in Activity - B and add a stage called onResume() which is called when you resume back to Activity B from A
Remove this:
#Override
public void onBackPressed(){
Intent i = new Intent(this, Game.class);
startActivity(i);
}
With this:
#Override
public void onBackPressed(){
super.onBackPressed();
}
When you coming back from A to B, in B #Override stage onResume() and in this you can save the value while coming back from Activity A.
Add this in Activity B:
#Override
protected void onResume() {
super.onResume();
// save values here for resume
}
Look the Activity Life Cycle:

Have to press Back button two times

I am trying to implement simple back button on activity to go to previous activity, but some weird behavior is happening when I am calling method finish() - the problem is I have to press back button TWO times? Why is this happening? In the back method i have only finish(). What is the other way to go to previous saved activity without instantiate a completely new Intent?
public void back1 (View view){
this.finish();
}
This is second try with the same result:
ImageButton buttonback = (ImageButton) findViewById(R.id.imageButton6);
buttonback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
You are most likely starting the activity twice.
When pressing back you are finishing one, and the other one is coming forward. Check your onCreate and onResume for anything that may be using intents or starting any activity
#Override
public void onBackPressed() {
super.onBackPressed();
}
add that to your code the super call closes the activity no need to call finish()
If you just want the devices back button to function, you dont need to override the onBackPressed method in Activity.
If you want to place a custom button in view and set back action to that button, then you need to write button clicklistener to the same
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});

How to update Activity from thread started in another activity?

I have a Main activity and after click on button I start thread (but the thread is hidden in library and I have only callback in Main activity.
Now I want to start another activity (call A) where I want to put results from the thread.
Below is simplified code:
public class Main extends Activity {
XManager.ResultsCallback xResultsCallback = new XManager.ResultsCallback() {
// the method is called every 10 sec.
#Override
public void onResult(ArrayList<String> texts) {
}
};
XManager xManager = new xManager(xResultsCallback);
View.OnClickListener onClick = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
XManager.start();
Intent i = new Intent(Main.this, A.class);
startActivity(i);
}
};
}
I want to update the content of A activity each time when onResult() method is called. How to do that?
Use LocalBroadcastManager,
In your Main Activity create function :
private void sendResult() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my result!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
and add BroadcastReceiver in your A Activity
private BroadcastReceiver onResult= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("jazzy","onReceive called");
}
};
add on OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
// Register to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
add onDestroy
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
I have a suggestion that you should do as follows:
Start Your Activity A on button click
Inside Activity A declare your XManager instance with a callback present in A itself
Then start your XManager as XManager.start(); that way you would be getting all the callbacks in your desired activity.
Have a great day!
I think if you want to decouple the logic, beside you can use the Android BroadcastReceiver, the another flexible choice is to use the Bus
And you can integrate it with gradle easily
dependencies {
compile 'com.squareup:otto:+'
}

onBackPressed() not working while coming from another activity

I have three activities: First, Second and Third. I used this method in Second activity:
public void onBackPressed() {
super.onBackPressed();
finish();
}
and this on Third activity:
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(Third.this, Second.class);
startActivity(i);
finish();
}
The problem is when I press back button after coming from the Third activity, I am going into First activity instead of finish(). I am successfully exiting the application when I click back button right after coming from first activity but not after coming from Third activity.
How to solve this problem?
EDIT: Thanks for the answers guys,the answer of "Ved Prakash" solved the problem for me.But i have a weird problem now.When i press back button the app is successfully exiting but the app which i minimized to Recent Apps button is coming on to the screen and exiting.For example,if i have opened Setting app before opening my app,when i press back button,my app is exiting and immediately Settings app is also opening and exiting itself.What might be the problem?
Your problem is that you don't seem to understand how Activities work. The finish() function ends the current Activity, and then you receive the previous Activity from the backstack.
My recommendation is that you should use a single Activity, and hold Fragments inside it. If you want it so that pressing the Back button ends the application at any screen that is displayed, you could do the following:
Activity XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/initial_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity that holds the Fragments:
public class InitialActivity extends FragmentActivity implements ReplaceWith
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial);
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.initial_container, new FirstFragment()).commit();
}
}
#Override
public void replaceWith(Fragment fragment)
{
getSupportFragmentManager().beginTransaction().replace(R.id.initial_container, fragment).commit();
}
}
Example for a Fragment:
public class FirstFragment extends Fragment implements View.OnClickListener
{
private ReplaceWith activity_replaceWith;
private ImageView exampleImage;
public FirstFragment()
{
super();
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_replaceWith = (ReplaceWith) activity;
}
catch (ClassCastException e)
{
Log.e(getClass().getSimpleName(), "Activity of " + getClass().getSimpleName() + "must implement ReplaceWith interface!", e);
throw e;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
exampleImage = (ImageView) rootView.findViewById(R.id.fragment_first_example_image);
exampleImage.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v)
{
if(v == exampleImage)
{
activity_replaceWith.replaceWith(new SecondFragment());
//please note that this should be done only if you are planning
//only on single-screen applications
//with no other layouts based on orientation or size
//otherwise, the Activity needs to be responsible for this, not the Fragment
}
}
}
This way, when you press the Back button, your application would end from any displayed screen.
Ok your code is wrong.
If you will look at activity source, you see that activity.onBackPressed() is calling finish(). So if call super.onBackPressed() you don't need to call finish.
Finish() is not stopping your application, it's stopping current activity.
Your code on third activity very strange. You are trying to stop activity and start another same activity.
What exactly you want to achieve?
If you want to exit application from your third activity, you need to clear your backstack. But I think you have problem with structure of your app.
Ok. then you should finish your first activity when you go to second activity like this(If you are using intent for that):
Intent it=new Intent(FirstActivity.this,SecondActivity.class);
finish();
startactivity(it);
and same for Second Activity:
Intent it=new Intent(SecondActivity.this,ThirdActivity.class);
finish();
startactivity(it);
this done your work...when you are in third activity the above activities are finished..
and when you press backButton you will be exit from application..
Good luck.
You can use -
public static final int 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 here is how -
When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "MainActivity".
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
This explanation part is also introduced at exit-an-android-app.

close an activity from other activity?

Does anyone know how to close an activity from other activity?? for example: i have 3 activity (activity A, B, and C) and from activity C, i can close an activity A..
my activity structure is activity A -> activity B -> activity C
how to close an activity A from activity C?
i was try this code :
#Override
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent goToLockScreen= new Intent(this,LockScreenForm.class);
startActivity(goToLockScreen);
finish();
but that code is only fot closing activity A from activity B, and can't close activity A from activity C direcly..
Does anyone know about closing an activity direcly from other activity??
thanks..
First Go to parent activity by starting it
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
switch(Code){
case A: go to that activity and finsih() this again come back to parent activity
case B: go to that activity and finsih() this again come back to parent activity
/////and son on
}
try It work perfectly for me
`public class aActivity extends Activity {
public static Activity handleToClose;
#Override
public void onCreate(Bundle savedInstanceState) {
.
.
.
handleToClose = this;
}
public void onClick(View v)
{
Intent i = new Intent(this, act2.class);
startActivity(i);
}
}`
Now You have to finish Activity-A from Activity-B
Activity-B or 2nd Activity
`public class act2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
// your code here
}
public void onClick(View v)
{
aActivity.handleToClose.finish(); //this will finish aActivity (1st Activity)
finish();//to finish current Activity
}
}`
Intent goToLockScreen= new Intent(this,LockScreenForm.class);
goToLockScreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This is a prescribed way and you should follow it.. if you want some other behaviour yo can implement it.. there are lot many questions asked on this topic.. refer other questions...
What about starting both B and C forResult and send a result back to pervious activity to let A finally call finish()? Like this:
A startActivityForResult() -> B startActivityForResult()-> C
C setResult()-> B onActivityResult(){setResult()} -> C onActivityResult(){finish()}
Sounds complicated, but maybe it can be used as a workaround?
try this
If the update activity is launching another installation activity, then you may want to override void onActivityResult(int requestCode, int resultCode, Intent intent) in the update activity, providing the following implementation. Also, when the update activity launches the installation activity, it should do so with startActivityForResult(Intent, int), not with startActivity(Intent).
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
finish();
}

Categories

Resources