我正在使用GoogleCientApi
对象来获取位置更新和其他Accelerometer
传感器,并每隔5秒将其发送到服务器。我想让它无休止地在后台运行,即24 * 7电池优化。没有什么需要在UI
更新。请建议是否使用Service
或IntentService
?如果使用Service
如何使用Handler
运行它?任何建议或文章链接都会有所帮助。
如果您想使用服务来实现这一点
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);
}
使用以下组件可以实现这一点
使用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