3

As i read No matter what time period you define in alarm manager it fires after every 1 minutes above sdk 21. I am running a service in which i want my method to execute after every 5 minutes. This is the code i have done

public class Servicebackground extends Service {
@Nullable
@Override

public IBinder onBind(Intent intent) {
    System.out.println("service started in onBind");
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Intent notificationIntent = newIntent(this,MyLocationListener.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 300000, pendingIntent);


    System.out.println("service started in on create");




    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    System.out.println("service stopped");

}


@Override
public void onCreate() {


        return;
    }


    public class MyLocationListener extends BroadcastReceiver implements LocationListener {

    @Override
    public void onReceive(Context context, Intent intent) {


        Intent  ii = new Intent(context, Servicebackground.class);
        startService(ii);
        }

In the class i am calling the service i have done

    startService(new Intent(this, Servicebackground.class));

But even if i have defined the time to be 5 minutes the method runs after every minute.I read that after sdk 21 no matter what time you define the method will execute after every 1 minute if you are using alarm manager.

Please tell me if there is any mistake. Or please suggest me any other way in which i would be able to run the service in background even if app is killed and the method executes after every 5 minutes.If there are other possible ways please suggest.

Vipin NU
  • 301
  • 2
  • 16

2 Answers2

1

Using handler and timertask

Timer timer;
TimerTask task;
private Handler handler;
@Override
protected void onCreate() {
    handler = new Handler();
    if (Build.VERSION.SDK_INT > 21) {
     startTimerTask();
   }
}

public void startTimerTask() {

    Log.w("--> ", "Start timer call");
    timer = new Timer();
    task = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                   executeMethod();
                }
            });
        }
    };
    timer.schedule(task, 0, 60000 * 5);
}

 private void executeMethod() {
   //   Do what you want
}
Chirag.T
  • 746
  • 1
  • 6
  • 18
-1

alaram setReating not work api 19 so you use handler to manually repeat process. refer AlarmManager fires alarms at wrong time

Handler handler;
    Timer timer;
    TimerTask doAsynchronousTask;
    public AlarmManager alarm;

onResume

Intent intent = new Intent(getActivity(),Services.class);

final Calendar cal = Calendar.getInstance();
        pintent = PendingIntent.getService(getActivity(), 0, intent, 0);
        alarm = (AlarmManager) getActivity().getSystemService(
                Context.ALARM_SERVICE);


            if (Const.DEVICE_API_INT < Const.ANROID_API_LOILLIPOP) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                        cal.getTimeInMillis(), 3 * 1000, pintent);
            } else {

                handler = new Handler();
                timer = new Timer();
                doAsynchronousTask = new TimerTask() {

                    @Override
                    public void run() {
                        handler.post(new Runnable() {

                            @SuppressLint("NewApi")
                            public void run() {
                                try {
                                    alarm.setExact(AlarmManager.RTC_WAKEUP,
                                            cal.getTimeInMillis(), pintent);

                                } catch (Exception e) { // TODO Auto-generated
                                                        // catch
                                }
                            }
                        });
                    }
                };
                timer.schedule(doAsynchronousTask, 0, 3000);

onCreate

 receiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {

                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {

                        int resultCode = bundle
                                .getInt(Services.RESULT);
                        if (resultCode == getActivity().RESULT_OK) {
                            trainingStatus = bundle
                                    .getString(Services.RESPONSE);
                            if (Status.equalsIgnoreCase("finished")) {

                                if (intent != null) {
                                    getActivity().stopService(intent);
                                }
                                alarm.cancel(pintent);
                            } else {

                            }

                    }
                }
            };

Service

@Override
    protected void onHandleIntent(Intent intent) {

        Log.e("TAG", " Training services start");

        Bundle extras = intent.getExtras();
publishResults(trainingStatus, resultInt);
}
private void publishResults(String response, int result) {
        Intent intent = new Intent(FILTER);
        intent.putExtra(RESPONSE, response);
        intent.putExtra(RESULT, result);
        sendBroadcast(intent);
    }
Community
  • 1
  • 1
RDY
  • 613
  • 1
  • 9
  • 25
  • It is better to explain your answer rather than simply dump a load of uncommented code on the user. – Kuffs Feb 02 '17 at 12:58
  • In fragment I use broadcast receiver. onResume I call service in every 3 seconds if receiver get correct result cancel alarm. I update fragment code check it – RDY Feb 04 '17 at 10:40