我想知道我是否可以这样做,我想实现一项服务,该活动将在活动启动时调用,并应定期运行,当我通过关闭或按下该服务停止活动应该停止并且报警管理器不应在活动重新启动之前调用服务。 还有一件事我想发送一些关于哪些服务可以运行并将结果返回给活动的数据。 目前我这样做......
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添加到清单
中请帮忙并建议怎么做?
答案 0 :(得分: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);
}