0

I have already developed a service that starts itself when activity is started. But i want to stop the service after certain interval say 10 seconds and again start service after some time say 30 seconds later. I am a little new to android programming so not getting how to do that , please help. I am using broadcast receiver for starting service.

user2661237
  • 11
  • 1
  • 3
  • possible duplicate of [how to schedule some code execution in android or: what exactly are daemon threads in android?](http://stackoverflow.com/questions/3883246/how-to-schedule-some-code-execution-in-android-or-what-exactly-are-daemon-threa) – Gusdor Aug 16 '13 at 11:35
  • use TimerTask or AlarmManager – AndroUser Aug 16 '13 at 11:36
  • Make the service post a pending intent to alarm manager, for when it needs to start again. – S.D. Aug 16 '13 at 11:40

3 Answers3

6

I would recommend using the alarm manager and sending a pending intent to start the service. Much like this:

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent serviceIntent = new Intent(context, ServiceReceiver.class); 
PendingIntent pi = PendingIntent.getBroadcast(context, ServiceIdsConstants.SERVICE_ID,     serviceIntent , PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 30000, pi);

Then in the BroadcastReceiver do this:

Intent intent = new Intent(context, MyServiceService.class);
context.startService(intent);
crysxd
  • 3,177
  • 20
  • 32
  • can alarm manager be used while working with wifimanager and bluetoothmanager? – user2661237 Aug 16 '13 at 14:18
  • I am not sure that I follow your question. Generally speaking Broadcast Receivers aren't given a lot of time to execute. You generally would start a service from them. Then using the services context you can get the bluetooth or wifi manager. – Delicious Software Aug 20 '13 at 01:15
  • Is there any reason to use am.getBroadcast(serviceIntent) here rather than just am.getService(MyServiceService) directly, bypassing the broadcast completely? – averasko Nov 27 '13 at 01:00
  • I believe I recommended the alarm manager because this user wanted to restart the service at a specific time in the future. – Delicious Software Dec 03 '13 at 12:19
  • 2
    fwiw, for anyone looking at this example, note that the 30000 parameter to am.set() doesn't mean "in 30 seconds", it means "at the wall clock timestamp 30000", which is sometime in December 1970, and so will immediately fire. You can get "30s in the future" via System.currentTimeMillis() + 30000 for this parameter instead. It's probably also worth using ELAPSED_REALTIME and SystemClock.elapsedRealtime() + 30000 instead of System.currentTimeMillis() in case the clock is reset. – Brian Duff May 27 '15 at 19:39
  • But if you need to schedule during the lifetime Google says: For timing operations that are guaranteed to occur during the lifetime of your application, instead consider using the Handler class in conjunction with Timer and Thread. This approach gives Android better control over system resources. (http://developer.android.com/intl/ru/training/scheduling/alarms.html) – Subtle Fox Apr 13 '16 at 14:13
2

You need to break your task down into more primitive parts than that. Then you can see what you need to google for and will get better results :)

  1. use a scheduler to schedule a new task on another thread
  2. 'sleep' the thread for X milliseconds.
  3. start your service using your intent and broadcastreceiver

Additionally (superior method), use the alarm manager how to schedule some code execution in android or: what exactly are daemon threads in android?

Community
  • 1
  • 1
Gusdor
  • 14,001
  • 2
  • 52
  • 64
0

Just wrote a utility that you and others can use :

public static void startDelayedWakefulService(Context context,long delayInMillis,Class<? extends Service> serviceClass) {
    AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent serviceIntent = new Intent(context, DelayedStartServiceBroadcastReceiver.class);
    serviceIntent.putExtra("className",serviceClass.getName());
    PendingIntent pi= PendingIntent.getBroadcast(context, 7, serviceIntent , PendingIntent.FLAG_UPDATE_CURRENT);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeInMillis()+delayInMillis, pi);
}

and

public class DelayedStartServiceBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String className = intent.getStringExtra("className");
        try {
            startWakefulService(context,new Intent(context,Class.forName(className)) );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            completeWakefulIntent(intent);
        }
    }
}

dont forget to add it to your manifest

    <receiver
        android:name=".utils.DelayedStartServiceBroadcastReceiver"
        android:enabled="true"
        android:exported="true" >
    </receiver>
Ofek Ron
  • 8,354
  • 13
  • 55
  • 103