问题
I am using GoogleCientApi
object to fetch location updates and other Accelerometer
sensors and send it to server every 5 sec . I want it to run in background endlessly i.e. 24*7 with battery optimisation. Nothing needs to be updated in UI
. Please suggest whether to use Service
or IntentService
?
If using Service
how to run it using Handler
? Any suggestion or article link will be helpful.
回答1:
If you want to achieve this using service
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
}
}
Also you need to register your service in AndroidManifest.xml
<service
android:name=".service.MyService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false" />
And call your service through Activity
if (!checkServiceRunning())
{
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
回答2:
This is posible with use of following component
Use Android Foreground Service for get current location while app open / close.
Note: Latest Android versions is not allowing to get current location through Backghround service.
Use Socket/Pusher for update location to user server.
Reference link
1). https://developer.android.com/guide/components/services.html
2). http://www.truiton.com/2014/10/android-foreground-service-example/
For Socket
1). https://socket.io/blog/native-socket-io-and-android/
2). https://github.com/socketio/socket.io-client-java
For Pusher
1). https://pusher.com/docs/android_quick_start
回答3:
I recommend you use alarms.
You can use services to continue executing code in background and wakelocks but I had to do something similar at what you describe and found out that services can be killed at any moment if the android system requires free memory.
The solution I found was to use alarms, if you schedule alarms this alarms will go off whether your app is still executing or not. That way my app could get the device position even though the system had killed the app due to lack of resources. It's the only solution I found that works in this scenario.
The idea came to me in some google i/o when they said that if you really need your app to continue no matter what you should use alarms instead of services.
Use exact amarms as inexact ones sometimes take, at least, 5 minutes until the alarm goes off.
来源:https://stackoverflow.com/questions/48047534/services-or-intent-services-to-send-location-updates-every-5-sec-to-server-endle