want to run and stop service with activity android

2019-05-16 13:18发布

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?

1条回答
劳资没心,怎么记你
2楼-- · 2019-05-16 13:50

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);

    }
查看更多
登录 后发表回答