嗨我需要停止已经在特定时间后启动的后台服务。我将从服务器获取停止服务的持续时间。我已经在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有关。请指导我
答案 0 :(得分:2)
试试:
将参数添加到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){
}
}
您也可以尝试在服务中使用Handler:
处理程序变量:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1: {
stopSelf();
}break;
}
}
}
延迟任务:
handler.sendEmptyMessageDelayed(1, 60 * 1000);
答案 1 :(得分:0)
创建计时器任务以停止服务并指定从服务器获取的延迟时间
Timer timer = new Timer ();
TimerTask hourlyTask = new TimerTask () {
@Override
public void run () {
// your code here to stop the service ...
}
};
//安排要运行的任务分配从服务器获取的时间(DelayTime)
timer.schedule (hourlyTask, DelayTime);
答案 2 :(得分:0)
那么特定的时间是什么。
您可以做一件事,记下服务的开始时间。如果要在指定的持续时间或特定时间后停止服务,请将系统当前时间与该时间进行比较,如果匹配则停止服务。这应该可以解决问题。
告诉我它是否适合你.. ======> 只需按照以下步骤操作:
答案 3 :(得分:0)
你必须创建一个广播接收器:
Calendar cal = Calendar.getInstance(); // this will return current time
// if you want to trigger after 1 minute then add into calender object
cal.add(Calendar.MINUTE, 1);
Intent intentAlarm = new Intent(this, AlarmReciever.class);
intentAlarm.setAction("My_Action");
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MainActivity.this, REQUEST_CODE, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
// set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
AlarmReciever .java
public class AlarmReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// call method to stop service
}
}
同样在清单文件中声明此AlarmReceiver类
<receiver android:name=".AlarmReciever" >
</receiver>
答案 4 :(得分:0)
> here i used the countdowntime for 30second
after 30second call stopself() method it will stop your
services..u can also do what ever u want on finsih you can also pass a
notification to the user....
new CountDownTimer(30000, 1000) {
@Override
public void onTick(long l) {
}
@Override
public void onFinish() {
//r u can also pass a notification
stopSelf();
}
}.start();