Question

I am starting a STICKY service in my mainActivity#create, but when user press the System Home or Back buttons, the service is not deserted…. any way ? should it not be STICKY ?

    MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
       ...
       startService(new Intent(this, FeedbackService.class));


    FeedbackService.java
    public class FeedbackService extends  Service implements OnInitListener {
    ….  
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
      //Log.i(TAG, "Received start id " + startId + ": " + intent);
      return START_STICKY; // run until explicitly stopped.
    }
Was it helpful?

Solution

This will confirm the user wants to exit before it kills the service.

@Override
public void onBackPressed() {
    final DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            switch (which) {
                case DialogInterface.BUTTON_POSITIVE:

                    super.onBackPressed();
                    stopService(intentName)

                case DialogInterface.BUTTON_NEGATIVE:
                    //No button clicked
                    break;
            }
        }
    };

    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you exit and stop the background process?").setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener).show();
}

OTHER TIPS

Override the onPause() method and add below code on onPause()

stopService(intent_name);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top