问题
I was trying to close app on click of button click.so i use the following code on home page
closebtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
finish();
}
});
from page5
clicking of close button
Home page opens.
b5.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent i =new Intent(Page5.this, FirstPage.class);
startActivity(i);
}
});
so when i click on close button in home page it is again going to page5 instead of closing app.
Please help me to find the problem
Thanks in advance.
回答1:
finish()
doesn't close the app. It only closes the current activity. So after finishing an activity the natural behavior is going back to the last activity of activity stack.
So now you have multiple options
- finish the previous activity before starting next one
- startactivityforresult to start second activity. When finished you can catch in onActivityResult to finish.
There are also other possible options.
回答2:
try this:
b5.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent i =new Intent(Page5.this, FirstPage.class);
startActivity(i);
Page5.this.finish();
}
});
回答3:
You Add following code for exit the app.
closebtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startMain);
}
});
By using this code when you click on close button you directly redirect to device home screen.
回答4:
you need to clear the top activity. May be you can try something like this
Suppose in our application, we have a number of activities(say ten) and we need to exit directly from this activity. What we can do is, create an intent and go to the root activity and set flag in the intent as
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
also, add some extra like boolean to the intent
intent.putExtra("EXIT", true);
Then in root activity, check the value of the boolean and according to that call finish(), in the onCreate() of the root activity
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
来源:https://stackoverflow.com/questions/17292405/exit-button-in-android-not-working