gpt4 book ai didi

android - 想要使用 Activity android 运行和停止服务

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:58 28 4
gpt4 key购买 nike

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

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

请帮助并建议如何去做?

最佳答案

开始:

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

}

关于android - 想要使用 Activity android 运行和停止服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16249202/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com