Search code examples
androidpreferenceactivityactivity-finish

How to close PereferenceActivity


i'm trying to close the preference activity after i click the back button..but when i press it then click the multi tasking button i see two activities opened for my app the one i'm currently on and the preferenceActvivty which i was on before i pressed back

this is my code

public class List extends PreferenceActivity {
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getFragmentManager().beginTransaction().replace(android.R.id.content, new SetFrag()).commit();
}

public static class SetFrag extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings_main);
    }
}
 @Override
public void onBackPressed() {
    super.onBackPressed();
    List.this.finish ();
}

Thanks for help.


Solution

  • I got the solution, Usually we need to code before super.onBackPressed() to be called.

    So change your code in to this

    public class List extends PreferenceActivity {
    // do some stuff
    @Override
    public void onBackPressed() {
    List.this.finish ();
    }
    

    Edit :

    So here is my final answer paste this custom exit activity in your package

    public class ExitActivity extends Activity
    {
    @SuppressLint("NewApi")
    @Override protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    
        if(android.os.Build.VERSION.SDK_INT >= 21)
        {
            finishAndRemoveTask();
        }
        else
        {
            finish();
        }
    }
    
    public static void exitApplication(Context context)
    {
        Intent intent = new Intent(context, ExitActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }
    }
    

    add in manifest

            <activity
            android:name=".ExitActivity"
            android:autoRemoveFromRecents="true"
            android:theme="@android:style/Theme.NoDisplay" />
    

    And call it with

    @Override
    public void onBackPressed() {
    ExitActivity.exitApplication(getApplicationContext());
    }
    

    Good luck