想用活动android运行和停止服务

cod*_*nic 3 android android-service

我想知道我是否可以这样做,我想实现一个服务,将在活动启动时调用,并应定期运行,当我通过关闭或按下停止活动时应该停止服务并且警报管理器不应该调用活动重新启动前的服务.还有一件事我想发送一些关于哪些服务可以运行并将结果返回给活动的数据.目前我这样做.....

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

 }

}
Run Code Online (Sandbox Code Playgroud)

MyBrodcastReceiver被添加到清单中

请帮忙并建议怎么做?

Bob*_*obs 9

开始:

this.startService(new Intent(this, MyService.class));
Run Code Online (Sandbox Code Playgroud)

停止:

this.stopService(new Intent(this, MyService.class));
Run Code Online (Sandbox Code Playgroud)

有间隔创建一个定期调用BrodcastReceiver的服务,如下例所示:

在您的服务中:

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

    }
Run Code Online (Sandbox Code Playgroud)