How to run foreground service with open Camera from another foreground service in Android 11?

Viewed 1675

I am testing now open camera in foreground service in Android 11 and I have problem with new Android 11 restrictions: https://developer.android.com/guide/components/foreground-services

Pseudo code:

//Service1 is started by JobScheduler.
class Service1 extends Service {
    ...
    startForeground(ID_OF_SERVICE1_NOTIFICATION, getService1Notification())
    ...
    //Run another foreground service with open camera
    Intent i = new Intent(getApplicationContext(), Service2.class)
    ContextCompat.startForegroundService(context, i)
    ...
}

class Service2 extends Service {
    ...
    startForeground(ID_OF_SERVICE2_NOTIFICATION, getService2Notification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST);
    openCamera() // <-- Policy exception
    ...
}

Class Service1 is started by JobScheduler with startForeground() and show notification to user. Service1 can start (ContextCompat.startForegroundService()) Service2 with startForeground() and show notification to user too. Service2 opens camera. The user sees notification all the time.

manifest edited:

<service android:name=".service.Service2"
    android:foregroundServiceType="camera|microphone"
    android:stopWithTask="false"/> 

Edited starForeground() in Service2 with flag FOREGROUND_SERVICE_TYPE_MANIFEST: (a special value indicates to use all types set in manifest file)

The result from Logcat:

Foreground service started from background can not have location/camera/microphone access: service com.example.test/.service.Service2

Tried also FOREGROUND_SERVICE_TYPE_CAMERA|FOREGROUND_SERVICE_TYPE_MICROPHONE.

I would like to keep the automation in starting the camera for user. Is there any way?

1 Answers

As far as I know, since android 11 there is no way to automatically start the camera from a foreground service, if the app was not visible to the user since the start of the app process. The user must interact with the application in order to be able to use the camera. According to the docs, these are the ways for an app to be considered interacted with, without actually opening an activity:

  • The service is started by a system component.
  • The service is started by interacting with app widgets.
  • The service is started by interacting with a notification. [note: Interacting! It is not enough to display the notification]
  • The service is started as a PendingIntent that is sent from a different, visible app.
  • The service is started by an app that is a device policy controller that is running in device owner mode.
  • The service is started by an app which provides the VoiceInteractionService. The service is started by an app that has the START_ACTIVITIES_FROM_BACKGROUND privileged permission.
Related