want to run and stop service with activity android

别等时光非礼了梦想. 提交于 2019-12-07 14:22:40

问题


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:


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

    }


来源:https://stackoverflow.com/questions/16249202/want-to-run-and-stop-service-with-activity-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!