I am breaking my head around it with no solution's so far. I seen many guides how to accomplish this (Documentation, Tutorial) and successfully made it happen in android 7. What I managed to do is successfully get notification with service running at background when user activity changed. My app works perfectly. The problem is with android 8 and google battery management. My service is always killed. So... What I already tried to overcome this problem:
Explain the user how to disable battery optimization for my app so it will not kill my service. The problem is its too comlicated for cummon user.
Add
uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"
and check it with code:
Intent intent = new Intent();
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (pm.isIgnoringBatteryOptimizations(packageName)){
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
}
else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
}
}
context.startActivity(intent);
But I undersood my app can be banned from play store, and this is big problem.
So how can I use ActivityRecognitionClient and always receive notification when activity changed even when my app is in background in android 8? Maybe connecting directly google service for this somehow?
Consider using a DetectedActivityFence
, part of the Awareness APIs. In this case it is the system that monitors and sends you broadcasts, so there's no need to run your own background service.
Once you receive a broadcast for a fence, you can use startForegroundService
to respond to the broadcast. This works even when your app is in the background and the corresponding user-facing notification will only be visible for a short while.