There is an application associated with geolocation transmission written under Android (Java) and the problem is that the transmission of geodata is interrupted when scolding or blocking the screen. I decided that the use of the Foreground service can solve the problem. How can I implement this service on a simple example?
Answer 1, Authority 100%
If you work with the location, you need the permission of Android.permission.access_background_location. This is a new permission to access location in the background.
Show you an example code that can be used. Dagger 2.28.3
is used for injection.
class EventRecorderservice: lifecycleservice () {
// Here all your dependencies, usually it is LiveData which supplies some data, such as location.
Override Fun OnCreate () {
super.oncreate ()
AndroidInjection.INject (this)
// Sign and process the result of your LiveData
}
Override Fun OnStartCommand (INTENT: INTENT, FLAGS: INT, STARTID: INT): INT {
// Creating that the alerts hanging in the curtain
VAL notification = notificationHelper.TrackingNotification (this)
.setcontentTitle (GetString (R.String.Notification_title))
.setContentText (GetString (R.String.Notification_Text))
.setvibrate (Longarrayof (0L))
.build ()
StartForeGround (notification_id, notification)
If (Intent.action == NULL) {
Timber.e ("Action Was Null, Flags = $ Flags + Bits = $ {integer.tobinaryString (Flags)}")
Return start_sticky
}
WHEN (Intent.action) {
Key_start - & gt; StartTracking ()
Key_Stop - & gt; StopTracking ()
}
RETURN SUPER.ONSTARTCOMMAND (INTENT, FLAGS, STARTID)
}
Private Fun StopTracking () {
// Example of the remains of the service
StopForeGround (True)
StopSelf ()
}
COMPANION OBJECT {
Private Const Val notification_id = 1
Private Const Val Key_start = "Start"
Private Const Val Key_Stop = "Stop"
FUN START (CONTEXT: CONTEXT) {
SendAction (CONTEXT, KEY_START)
}
Fun Stop (CONTEXT: CONTEXT) {
SendAction (CONTEXT, KEY_STOP)
}
Private Fun SendAction (CONTEXT: CONTEXT, ACTION: STRING) {
Val Intent = Intent (Context, EventRecorderservice :: Class.java)
INTENT.Action = Action.
CONTEXTCOMPAT.STARTFOREGROUNDSERVICE (CONTEXT, INTENT)
}
@Suppress ("Deprecation")
FUN ISRUNNING (CONTEXT: CONTEXT): Boolean {
// This check is running whether the service is running, alerts may be disconnected for your application, it must be checked
Val Manager = Context.GetSystemService (Context.Activity_Service) AS ActivityManager
For (Service In Manager.GetrunningServices (integer.max_value)) {
if (EventRecorderservice :: class.java.name == service.service.classname) {
Return True.
}
}
Return False
}
@Workerthread.
FUN AUTOLAUNCHSERVICE (CONTEXT: CONTEXT) {
// there is some launch logic that will solve the service or not
START (CONTEXT)
}
}