要运行和活动的Android一条龙服务 [英] want to run and stop service with activity android
问题描述
我想知道如果我能做到这一点,我想实现一个将被调用时,活动启动,并应定期运行服务,当我通过关闭或pressing停止活动后面的服务应该停止并且活动重新推出之前报警经理不应该调用服务。
还有一件事我要发哪些服务可以操作,让结果返回到活动的一些数据。
目前我做这样的......
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加入到清单
MyBrodcastReceiver is added into manifest
请帮忙,并建议该怎么办呢?
please help and suggest how to do it?
推荐答案
启动:
this.startService(new Intent(this, MyService.class));
有关回采:
this.stopService(new Intent(this, MyService.class));
对于具有间隔创建定期调用BrodcastReceiver类似于下面的示例服务:
for having intervals create a service that calls a BrodcastReceiver periodically like the following sample:
在你的服务:
// 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);
}
这篇关于要运行和活动的Android一条龙服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!