服务或意图服务每5秒向服务器无休止地发送位置更新?

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

我正在使用GoogleCientApi对象来获取位置更新和其他Accelerometer传感器,并每隔5秒将其发送到服务器。我想让它无休止地在后台运行,即24 * 7电池优化。没有什么需要在UI更新。请建议是否使用ServiceIntentService?如果使用Service如何使用Handler运行它?任何建议或文章链接都会有所帮助。

android service geolocation android-volley android-intentservice
3个回答
1
投票

如果您想使用服务来实现这一点

    public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) 
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
        // This schedule a runnable task every x unit of time
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() 
        {
            public void run() 
            {
                callAPI();
            }
        }, 0, 10, TimeUnit.SECONDS);
        return START_STICKY;
    }

    @Override
    public void onDestroy() 
    {
        super.onDestroy();
    }

    public void callAPI() 
    {
    //Upload data to server and do your stuff
    }
}

您还需要在AndroidManifest.xml注册您的服务

<service
        android:name=".service.MyService"
        android:enabled="true"
        android:exported="true"
        android:stopWithTask="false" />

并通过活动致电您的服务

if (!checkServiceRunning()) 
    {
        Intent intent = new Intent(MainActivity.this, MyService.class);
        startService(intent);
    }

0
投票

使用以下组件可以实现这一点

使用Android前台服务获取应用打开/关闭时的当前位置。

注意:最新的Android版本不允许通过后台服务获取当前位置。

使用Socket / Pusher更新位置到用户服务器。

参考链接

1)。 https://developer.android.com/guide/components/services.html

2)。 http://www.truiton.com/2014/10/android-foreground-service-example/

对于Socket

1)。 https://socket.io/blog/native-socket-io-and-android/

2)。 https://github.com/socketio/socket.io-client-java

对于Pusher

1)。 https://pusher.com/docs/android_quick_start


0
投票

我建议你使用闹钟。

您可以使用服务继续在后台和wakelocks中执行代码,但我必须在您描述的内容中执行类似操作,并发现如果Android系统需要空闲内存,服务可以随时被杀死。

我找到的解决方案是使用alarms,如果您安排警报,无论您的应用程序是否仍在执行,此警报都会消失。这样,即使系统由于缺乏资源而杀死了应用程序,我的应用程序也可以获得设备位置。这是我发现在这种情况下有效的唯一解决方案。

当他们说如果你真的需要你的应用程序继续,无论你应该使用什么警报而不是服务时,这个想法来到我的谷歌i / o。

使用精确的amarms作为不精确的amarms有时需要至少5分钟,直到闹钟响起。

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