Search code examples
androidtimeandroid-servicealarmmanager

Stop the background service after particular time in android


Hi i need to stop the Background service which is already started after particular time.I will get the duration from server for when to stop the service.I have tried the Alarm Manager in android.

        Calendar cal = Calendar.getInstance();

        Intent intent = new Intent(context, MyService.class);
        PendingIntent pintent = PendingIntent.getService(context, 0, intent, 0);

        AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        // Start every 30 seconds
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*1000, pintent);
        Log.e(TAG, "Service started in Activity");

This above code is starting the service after every one minute.But i dont want to start the service.I need to stop the service after a minute.How to do that.Is that possible to do with Alarm Manager.Please guide me.


Solution

  • Try that:

    add parameter to your pendingIntent

    Intent intent = new Intent(context, MyService.class);
    intent.putExtra("param_name", "end");
    PendingIntent pintent = PendingIntent.getService(context, 0, intent, 0);
    

    Override onStartCommand() method in your Service

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try{
            String parameter = intent.getStringExtra("param_name");
            if(parameter.equals("end")){
                stopSelf();
            }
        }catch(Exception ex){
        }
    }
    

    Also you can try to use Handler in your service:

    Handler variable:

    private Handler handler = new Handler() {
    
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    stopSelf();
                }break;
            }
        }
    }
    

    Delayed task:

    handler.sendEmptyMessageDelayed(1, 60 * 1000);