want to run and stop service with activity android

android, android-service

Solution

for starting:

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

for stoping:

this.stopService(new Intent(this, MyService.class));

for having intervals create a service that calls a BrodcastReceiver periodically like the following sample:

in your service:

// An alarm for rising in special times to fire the pendingIntentPositioning
private AlarmManager alarmManagerPositioning;
// A PendingIntent for calling a receiver in special times
public PendingIntent pendingIntentPositioning;

@Override
        public void onCreate() {
            super.onCreate();

            alarmManagerPositioning = (AlarmManager) getSystemService
                    (Context.ALARM_SERVICE);

            Intent intentToFire = new Intent(
                    ReceiverPositioningAlarm.ACTION_REFRESH_SCHEDULE_ALARM);

            pendingIntentPositioning = PendingIntent.getBroadcast(
                    this, 0, intentToFire, 0);



        };


@Override
    public void onStart(Intent intent, int startId) {

            long interval = 10 * 60 * 1000;
            int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
            long timetoRefresh = SystemClock.elapsedRealtime();
            alarmManagerPositioning.setRepeating(alarmType,
                    timetoRefresh, interval, pendingIntentPositioning);

    }

Problem

I am wondering if i can do this, i want to implement a service that will be called when activity launches and should run at regular intervals, and when i stop the activity by closing or pressing back the service should stop and alarm manager should not invoke service before the activity relaunches. One more thing i want to send some data on which service can operate and give results back to activity. currently i am doing like this..... ``` class MyService extends Service{ } class MyScheduler extends BroadCastReceiver{ //Here alarm manager and pending intent is initialized to repeat after regular intervals. } class MyActivity extends Activity{ onCreate(){ //here i am binding the service } } ``` MyBrodcastReceiver is added into manifest please help and suggest how to do it?

Original source