可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to quit application through button click.
the code for button click is
quitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { // TODO Auto-generated method stub MainActivity.this.finish(); } });
But it require two clicks to exit from the app.
回答1:
use this code...i hope this will help you..
quitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { finish(); moveTaskToBack(true); } });
回答2:
use this it is work for me:
quitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { moveTaskToBack(true); MainActivity.this.finish(); } });
回答3:
the app must be quit in the first activity (MainActivity) in the stack (usually the first activity which is lauched when the app starts). I'm using this code:
finish(); android.os.Process.killProcess(android.os.Process.myPid());
both lines are important. Only killing is not sufficiant since Android may start your app again automatically, therefore finish() must also be used.
If you want to quit your app from another activity, first go back to the MainActivity and quit it from there. To go back I use this code:
Intent i = new Intent(context, MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(i);
This will call onCreate of the MainActivity. Using a static variable (in the application context) I set a flag if I want to quit in onCreate or not.
回答4:
What you need to do is to add this command on button click finishAffinity();
to close every active activity.
quitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { finishAffinity(); }});
回答5:
Try this it might help you.
quitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); } });
Edit the manifest file
<activity android:name=".HomeActivity" android:label="@string/app_title_home" android:clearTaskOnLaunch="true" />
回答6:
You can avoid all these confusions if you just had given the onClick()
function in your xml file. It will handle the View.OnClickListener()
Read below link for more information on how is XML implementation different from View.OnClickListener()
How exactly does the android:onClick XML attribute differ from setOnClickListener?
回答7:
To finish an activity or exit the app
@Override public void onBackPressed() { this.finish(); }