1

My Idea was, When destroys the app, I want to show them Alert Dialog after destory my app. I am only practicing, I think it can be done maybe my way is bad but i did this and its not working.code is below:

public class MainActivity extends AppCompatActivity implements

View.OnClickListener {
    Button btnStart, btnStop;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnStart = (Button) findViewById(R.id.btnstart);
        btnStart.setOnClickListener(this);
        btnStop = (Button) findViewById(R.id.btnstop);
        btnStop.setOnClickListener(this);

        intent = new Intent(MainActivity.this, MyService.class);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnstart:
                startService(intent);
                Toast.makeText(MainActivity.this, "Service Started", Toast.LENGTH_SHORT).show();
                break;

            case R.id.btnstop:
                stopService(intent);
                Toast.makeText(MainActivity.this, "Service Stopped", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                stopService(intent);
            }
        }).setMessage("Do you want to play Music in Background?").setTitle("Wait please...").create().setCancelable(false);
        builder.show();
    }
}
shilovk
  • 11,718
  • 17
  • 75
  • 74
Apple Appala
  • 329
  • 4
  • 16

1 Answers1

4

You shouldn't try to display anything in onDestroy(). If you want to alert the user before closing the app, you can override the "back" button.

@Override
public void onBackPressed() {
    ...
}
Amir Uval
  • 14,425
  • 4
  • 50
  • 74
  • I can call stopService(intent) in destory but why not AlertDialog? – Apple Appala Jul 24 '16 at 08:10
  • 1
    onDestroy is not a good place for anything that is critical to your app logic, since it is not guaranteed to be called. You can stop services from onPause for example. – Amir Uval Jul 24 '16 at 08:15