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.
- Use foreground service with persistent notification. The problem is its very anoin to user to see this ongoing and sometimes irrelevant notification.
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?