Skip to content

User Information

As an application developer, you can use the UserService API to retrieve the user name, user id, roles, and other information associated with the user. SAP Cloud Platform Mobile Services allows administrators to assign various roles to a user, which can be used to build flexible UIs for mobile application based on those roles.

suspend fun retrieveUser(): ServiceResult<User> = withContext(IO) { ... }
fun retrieveUser(listener: ServiceListener<User>) { ... }

For Kotlin client code, the first function can be used to retrieve the user information on the IO thread. The second function will retrieve user information and notify the result on the UI thread.

Sample Usage

The following sample code shows how to use this API.

UserService s = new UserService();
s.retrieveUser(result -> {
            if (result instanceof ServiceResult.SUCCESS) {
                Log.d(
                        "TEST",
                        ((ServiceResult.SUCCESS) result).getData().toString()
                );
            } else {
                Log.e("TEST", ((ServiceResult.FAILURE) result).getMessage());
            }
        });
CorotineScope().launch {
        when(val result = UserService().retrieveUser()) {
            is ServiceResult.SUCCESS -> {
                Log.d("Test", result.data!!.userName)
            }
            is ServiceResult.FAILURE -> Log.e("TEST", result.message)
        }
    }

To retrieve user information automatically when the mobile app is brought to the foreground or the user is authenticated, the following code can be referenced:

List<`MobileService`> services = new ArrayList<>();
UserService userService = new UserService(result -> {
    if(result instanceof ServiceResult.SUCCESS) {
        ...
    } else {
        ...
    }
});
services.add(userService);
SDKInitializer.INSTANCE.start(this, services.toArray(new MobileService[0]), null);
val services = mutableListOf<MobileService>()
val userService = UserService(object : ServiceListener<User> {
    override fun onServiceDone(result: ServiceResult<User>) {
        when (result) {
            is ServiceResult.SUCCESS -> Log.d("TEST", "User: ${result.data?.toString()}")
            is ServiceResult.FAILURE -> Log.e("TEST", "Error: ${result.message}")
        }
    }
})
services.add(userService)
SDKInitializer.start(this, * services.toTypedArray())

Last update: October 6, 2020