android服务以指定间隔连续执行任务

问题描述 投票:2回答:3

经过长时间的搜索,我仍然感到困惑,尽管我发现了一些相关的帖子,但是他们没有回答我想要的内容。在我的场景中,我想以固定的时间间隔(例如每5分钟一次)将用户的经纬度发送到服务器。为此,我使用了具有自己进程的服务,以便在Activity被销毁时不会被杀死,并且在服务方法onStartCommand中,我使用了while循环,该循环始终为真,并且在该循环中,我更新了服务器的位置并通过以下方式给出了延迟thread.sleep如下所示

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
   While(true)
           {
            Location currentLocation = getLocation();
            updateLocationToServer(currentLocation);
            try
               {
                Thread.sleep(300000)
               }
            catch(Exception e)
               {
                e.printStackTrace()
               }
           }
return Service.START_STICKY;

这里我无法理解return语句是不可达的,那么当服务被破坏时,如何在服务为后台进程的同时使用thread.sleep导致ANR(应用程序无响应)时如何自动重新启动服务,而我却发现它直接运行在UI线程中,这些信息使我感到困惑,在这种情况下,获得所需功能的最佳方法是什么。

java android android-service
3个回答
3
投票

您应该使用和AlertManager代替!

AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);

http://justcallmebrian.com/?p=129


1
投票
secondly using thread.sleep causing ANR (Application Not Responding) while service is a background process

来自http://developer.android.com/reference/android/app/Service.html

请注意,服务与其他应用程序对象一样,在其托管过程的主线程中运行。


0
投票

改为尝试使用警报管理器,请参见此示例how to set it to repeat every 5 minutes

© www.soinside.com 2019 - 2024. All rights reserved.