Search code examples
androidintentfilteronbackpressed

how to exit application using onbackpressed?


I have two activities in my project.. I set intent-filter in my first activity..Now I have one button in my first activity,after click on that it will redirect to second activity..and I added some code in my second activity's onbackpress to close the app,but instead of close app it goes to first activity..can any one tell me what is mistake..

public class First extends ActionBarActivity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn=(Button)findViewById(R.id.first);
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent=new Intent(First.this,Second.class);
            startActivity(intent);

        }
    });
}

SecondActivity.java

public class Second extends Activity{


private Button btns;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
    btns=(Button)findViewById(R.id.secs);
}

void Showtoast(String message) {
Toast.makeText(Second.this, message, Toast.LENGTH_LONG).show();}
private Boolean exit = false;

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    if (exit) 
    {
        finish(); // finish activity
    } else 
    {
        Toast.makeText(this, "Press Back again to Exit.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() 
        {
            @Override
            public void run()
            {
                exit = false;
            }
        }, 3 * 1000);

    }
}

Manifest

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.close_app_example"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".First"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="Second"></activity>
</application>

when i click on back button it shows first page instead of close app see images

enter image description here

enter image description here


Solution

  • finish first activity when you are moving to second activity.

    use

            Intent intent=new Intent(First.this,Second.class);
            finish()
            startActivity(intent);