3

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

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 添加到清单中

请帮助并建议如何做?

4

1 回答 1

9

开始:

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

停止:

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

为了有间隔创建一个定期调用 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);

    }
于 2013-04-27T06:59:28.380 回答