How to Finish an Android Application

How to finish an android application?

whenever you are starting a new activity use

myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myintent);

and in manifest file mention that activity as

<activity android:name=".<Activity Name>" >
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>

Closing Application with Exit button

Below used main.xml file

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/txt1" android:text="txt1" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/txt2" android:text="txt2"/>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/btn1"
android:text="Close App" />
</LinearLayout>

and text.java file is below


import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class testprj extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
}
}

how to finish all activities and close the application in android?

There is finishAffinity() method that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.

Programmatically Exit Android Application Without finish()

Use finish() in your splash screen just before you create your second activity, then use finish() is the second activity: that will not bring back the splash screen.

How to close Android application?

Just to answer my own question now after so much time (since CommonsWare commented on the most popular answer telling we should NOT do this):

When I want to quit the app:

  1. I start my first activity (either splash screen, or whatever activity is currently at the bottom of the activity stack) with FLAG_ACTIVITY_CLEAR_TOP (which will quit all the other activities started after it, which means - all of them). Just make to have this activity in the activity stack (not finish it for some reason in advance).
  2. I call finish() on this activity

This is it, works quite well for me.



Related Topics



Leave a reply



Submit