在Android中特定时间后停止后台服务 [英] Stop the background service after particular time in android
问题描述
我需要停止在特定时间后已经启动的后台服务。我将从服务器获取停止服务的持续时间。我已经在android中尝试了警报管理器。
Hi i need to stop the Background service which is already started after particular time.I will get the duration from server for when to stop the service.I have tried the Alarm Manager in android.
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(context, MyService.class);
PendingIntent pintent = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*1000, pintent);
Log.e(TAG, "Service started in Activity");
上面的代码每隔一分钟就会启动一次服务。但是我不想启动该服务。我需要在一分钟后停止该服务。该怎么做。是否可能与Alarm Manager有关。请指导我。
This above code is starting the service after every one minute.But i dont want to start the service.I need to stop the service after a minute.How to do that.Is that possible to do with Alarm Manager.Please guide me.
推荐答案
尝试:
向您的pendingIntent添加参数
add parameter to your pendingIntent
Intent intent = new Intent(context, MyService.class);
intent.putExtra("param_name", "end");
PendingIntent pintent = PendingIntent.getService(context, 0, intent, 0);
覆盖 onStartCommand()服务中的方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try{
String parameter = intent.getStringExtra("param_name");
if(parameter.equals("end")){
stopSelf();
}
}catch(Exception ex){
}
}
也可以尝试在服务中使用处理程序 :
Also you can try to use Handler in your service:
处理程序变量:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1: {
stopSelf();
}break;
}
}
}
延迟的任务:
handler.sendEmptyMessageDelayed(1, 60 * 1000);
这篇关于在Android中特定时间后停止后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!