在安卓系统中,如何在特定时间后停止后台服务?

3

你好,我需要在特定时间后停止已经启动的后台服务。服务器会告诉我需要运行的时间。我已经尝试使用Android中的Alarm Manager。

        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吗?请指导。


在一分钟过去后,只需调用stopService()吗?使用一个定时器或本地广播接收器。 - undefined
我不知道确切的时间。这里举个例子,我提到了一分钟。 - undefined
时间从您的服务开始时开始计算,从那个时间点开始计算一分钟?或者如果您从服务器获取时间持续时间,则可以创建一个通用函数,该函数接受时间持续时间并运行一个线程来执行相应的持续时间,并相应地调用stopService函数。简单吧? - undefined
请查看下面提供的答案。 - undefined
5个回答

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

Handler变量:

private Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1: {
                stopSelf();
            }break;
        }
    }
}

延迟任务:

handler.sendEmptyMessageDelayed(1, 60 * 1000);

嗨,谢谢您的回复。我在Service类中尝试了OnStartCommand代码。但是我得到了“PENDING_EXTRA_ACTION无法解析为变量”的错误。请帮助我。 - undefined
对不起,我回答了一些错误的内容。请使用"param_name"代替。我已经更新了我的帖子。 - undefined
注意:只有在您想要停止服务时才需要使用该参数。 - undefined
谢谢。它正在工作,但是onStartCommand立即被调用了。但是我需要在几分钟或几小时后调用。请指导我。 - undefined
在API级别5中,onStart()方法已被弃用。请参考http://developer.android.com/reference/android/app/Service.html#onStart(android.content.Intent, int)。 - undefined
显示剩余2条评论

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

1
请不要仅仅发布代码作为答案,还要提供解释您的代码是如何工作以及如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同票。 - undefined
好的,谢谢你的建议,我会尽量解释代码的内容。 - undefined

0

那么,什么是特定时间呢。

你可以做一件事,记下服务的开始时间。如果你想在指定的持续时间或特定时间之后停止服务,获取系统当前时间并将其与那个时间进行比较,如果匹配,则停止服务。这应该解决问题。

告诉我它是否对你有效...

======> 只需按照下面提供的步骤操作:

  1. 使用sharedprefrence保存服务的开始时间。
  2. 如果您对sharedprefrence不熟悉,请参考以下链接:http://examples.javacodegeeks.com/android/core/content/android-sharedpreferences-example/
  3. 然后在服务的onStart方法中获取系统当前时间,如果时间匹配则停止服务。

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

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>

我已经尝试了你的代码。但是AlarmReceiver类没有被调用。我在AlarmReceiver被调用后使用日志打印了一些内容,但是logcat中没有显示任何东西。 - undefined
譯文:警報接收器未被調用,我認為你在清單文件中沒有聲明它。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接