I'm developing a health application that record the user's steps. I'm really searching for a couple of weeks how to run this in the background and I have no solution yet.
runing service for long time without draing battery and system resource was hardest thing i faced in programming and finally today i found the best solution for my idea thank to Coding in Flow channel
StepsService::class
class MainActivity() : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"background_service"
).setMethodCallHandler(
MethodCallHandler { call: MethodCall, result:
MethodChannel.Result ->
if ((call.method == "start")) {
//start Service.
val i: Intent = Intent(
getApplicationContext(),
StepsService::class.java
)
ContextCompat.startForegroundService(this, i)
}
result.success(1)
}
//start Service.
)
}
}
StepsService::class
/** The service is starting, due to a call to startService() */
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.v("Service", "Start")
sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
stepCounterSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
stepDetectorSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
sensorManager!!.registerListener(this, stepCounterSensor, 0)
sensorManager!!.registerListener(this, stepDetectorSensor, 0)
//currentStepCount = 0;
currentStepsDetected = 0
stepCounter = 0
newStepCounter = 0
// --------------------------------------------------------------------------- \\
// ___ (3) start handler ___ \\
// remove any existing callbacks to the handler
handler.removeCallbacks(updateBroadcastData)
// call our handler with or without delay.
handler.post(updateBroadcastData) // 0 seconds
// ___________________________________________________________________________ \\
val notificationIntent = Intent(
this,
MainActivity::class.java
)
val pendingIntent = PendingIntent.getActivity(
this,
0, notificationIntent, 0
)
val notification : Notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notification = Notification.Builder(this, channelId)
.setContentTitle("$currentStepsDetected Steps")
.setContentText("Target Steps 7500")
.setSmallIcon(R.mipmap.ic_notification)
.setContentIntent(pendingIntent)
.setVisibility(Notification.VISIBILITY_PRIVATE)
.build()
}else{
notification = Notification.Builder(this)
.setContentTitle("Example Service")
.setContentText("description")
.setSmallIcon(R.mipmap.ic_notification)
.setContentIntent(pendingIntent)
.setVisibility(Notification.VISIBILITY_PRIVATE)
.build()
}
startForeground(1, notification)
return START_NOT_STICKY
}