Dynamically obtain camera and audio recording permissions using an SDK
Updated at:
This topic describes how to dynamically obtain camera and microphone permissions.
1. Dynamically obtain permissions for the Android SDK
1.1. Dynamically obtain camera permissions
1.1.1. Configure the AndroidManifest.xml file
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:debuggable="true"
android:extractNativeLibs="true" //Required
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Aspdemo"
tools:ignore="HardcodedDebugMode">1.1.2. Configure the cloud phone instance
//Disable the SDK from obtaining local device permissions on start.
bundle.putBoolean(StreamView.CONFIG_TAKE_PERMISION_REQ, false);
//Or
IASPEngine engine = mBuilder.takePermissionReq(false).enableRTC(true).build(context);
//Disable the SDK from loading the local camera by default.
mStreamView.enableSDKLoadCpdToStart(false);
1.1.3. Listen for cloud phone requests for local camera permissions
mStreamView.getASPEngineDelegate().addDataChannel(new DataChannel("wy_vdagent_default_dc") {
@Override
protected void onConnectStateChanged(DataChannelConnectState state) {
Log.i(TAG, "wy_vdagent_default_dc dc connection state changed to " + state);
}
@Override
protected void onReceiveData(byte[] buf) {
String str = "";
try {
str = new String(buf, "UTF-8");
} catch (UnsupportedEncodingException e) {
str = new String(buf);
}
Log.i(TAG, "wy_vdagent_default_dc dc received " + buf.length + " bytes data:" + str);
CommandUtils.parseCommand(str, new CommandUtils.CommandListener() {
@Override
public void onCameraAuthorize() {
checkStartCpd();
}
@Override
public void onRotation(int rotation) {
//Cloud phone rotation status
}
@Override
public void onUnknownCommand(String cmd) {
showError("Unknown command: " + cmd);
}
});
}
});package com.example.aspdemo.cloudphone.Util;
import android.util.Log;
import org.json.JSONObject;
public class CommandUtils {
public interface CommandListener {
void onCameraAuthorize();
void onRotation(int rotation);
void onUnknownCommand(String cmd);
}
public static void parseCommand(String data, CommandListener listener) {
try {
// Standardize prefix handling
String jsonStr = data.replaceFirst("^data:", "").trim();
JSONObject json = new JSONObject(jsonStr);
if (json.has("action")) {
String action = json.getString("action");
handleCommand(action, json, listener);
}
else if (json.has("cmd")) {
String cmd = json.getString("cmd");
handleCommand(cmd, json, listener);
}
} catch (Exception e) {
Log.e("CommandUtils", "Parsing failed: " + data, e);
}
}
private static void handleCommand(String cmd, JSONObject json, CommandListener listener) {
if (listener == null) return;
try {
switch (cmd) {
case "authorizeCamera":
listener.onCameraAuthorize();
break;
case "rotation":
listener.onRotation(json.getInt("value"));
break;
// Add other commands...
default:
listener.onUnknownCommand(cmd);
}
} catch (Exception e) {
Log.e("handleCommand", "Failed: ", e);
}
}
}1.1.4. Handle permission requests
private void checkStartCpd() {
runOnUiThread(() -> {
if (checkCameraPermission()) {
startCpd();
} else {
requestMultiplePermissions();
}
});
}
private void startCpd() { //Load the local camera
Log.i(TAG, "to startCpd");
mStreamView.getEngine().startCpd();
}
private boolean checkCameraPermission() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED;
}
private void requestMultiplePermissions() {
Log.i(TAG, "requestMultiplePermissions ");
String[] permissions = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO
};
ActivityCompat.requestPermissions(
this,
permissions,
MULTI_PERMISSION_REQUEST_CODE
);
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MULTI_PERMISSION_REQUEST_CODE) {
handleMultiPermissionResult(permissions, grantResults);
}
}
private void handleMultiPermissionResult(String[] permissions, int[] grantResults) {
boolean allGranted = true;
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
allGranted = false;
break;
}
}
if (allGranted) {
// All permissions are granted
startCpd();
} else {
// A permission was denied
handlePermissionDenied();
}
}
// Handle cases where a permission is denied
private void handlePermissionDenied() {
// Check if the user selected "Don't ask again"
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
// Display a dialog box to guide the user to the Settings page
new AlertDialog.Builder(this)
.setTitle("Permission permanently denied")
.setMessage("You have permanently denied camera permission. To use this feature, go to Settings and manually enable the permission.")
.setPositiveButton("Go to Settings", (dialog, which) -> openAppSettings())
.setNegativeButton("Cancel", null)
.create()
.show();
} else {
Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show();
}
}
// Open the application settings page
private void openAppSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}1.2. Dynamically obtain audio recording permissions
1.2.1. Configure the AndroidManifest.xml file
<uses-permission android:name="android.permission.RECORD_AUDIO" />1.2.2. Monitoring a cloud phone requires microphone permission on the local device
mStreamView.getASPEngineDelegate().registerSystemPermissionListener(new IRequestSystemPermissionListener() {
@Override
public boolean onRequestSystemPermission(SystemPermission systemPermission) {
Log.i(TAG, "onRequestSystemPermission " + systemPermission);
if (systemPermission == RECORD_AUDIO) {
if (!checkAudioPermission()) {
new Handler(Looper.getMainLooper()).post(() -> {
requestAudioPermission();
});
return false;
}
return true;
}
return false;
}
});1.2.3. Handle permission requests
private boolean checkAudioPermission() {
return ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
}
private void requestAudioPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this, Manifest.permission.RECORD_AUDIO)) {
// Display an explanation dialog box
new androidx.appcompat.app.AlertDialog.Builder(this)
.setTitle("Microphone permission required")
.setMessage("This feature requires microphone access to record audio.")
.setPositiveButton("OK", (dialog, which) -> {
// Request permission
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.RECORD_AUDIO},
AUDIO_PERMISSION_REQUEST_CODE
);
})
.setNegativeButton("Cancel", null)
.show();
} else {
// Directly request permission
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.RECORD_AUDIO},
AUDIO_PERMISSION_REQUEST_CODE
);
}
}2. Dynamically obtain camera permissions for the iOS SDK
2.1. Configure the info.plist file
Audio recording permission
Privacy - Microphone Usage Description
Camera permission
Privacy - Camera Usage Description2.2. Configure the cloud phone instance
//Disable the SDK from loading the local camera by default.
streamView.enableSDKLoadCpdToStart = false;2.3. Listening to the cloud phone requires local camera permission
@implementation DemoEDSAgentChannel
- (void)onConnectStateChanged:(ASPDCConnectState)state {
NSLog(@"[DemoEDSAgentChannel] onConnectStateChanged %ld", state);
}
- (void)onReceiveData:(NSData * _Nonnull)buf {
NSString *string = [[NSString alloc] initWithData:buf encoding:NSUTF8StringEncoding];
NSLog(@"[DemoEDSAgentChannel] onConnectStateChanged %@", string);
[CommandUtils parseCommand:string listener:self];
}
#pragma mark - CommandListener
- (void)onCameraAuthorize {
NSLog(@"[DemoEDSAgentChannel] onCameraAuthorize");
dispatch_async(dispatch_get_main_queue(), ^{
[self requestCameraPermission];
});
}
- (void)requestCameraPermission {
if ([AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)]) {
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
switch (status) {
case AVAuthorizationStatusNotDetermined:
// The user has not yet granted authorization. Request permission.
[self requestAccess];
break;
case AVAuthorizationStatusAuthorized:
// Authorization has been granted. Start the camera directly.
[self.streamView startCpd];
break;
case AVAuthorizationStatusDenied:
case AVAuthorizationStatusRestricted:
// Permission was denied or restricted. Display a prompt.
[self showPermissionDeniedAlert];
break;
}
} else {
NSLog(@"DemoEDSAgentChannel The device does not support a camera");
[self showNoCameraAlert];
}
}
- (void)requestAccess {
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if (granted) {
NSLog(@"DemoEDSAgentChannel Camera permission granted");
[self.streamView startCpd];
} else {
NSLog(@"DemoEDSAgentChannel Camera permission denied");
[self showPermissionDeniedAlert];
}
}];
}3. Dynamically obtain permissions for the Web SDK
3.1. Disable camera use on connection
connConfig: {
disableCamera: true,
}3.2. Monitoring the Cloud Phone requires local camera permission
//Configure dataChannelConfig in sessionParam
dataChannelConfig: [{
dataChannelName: 'wy_vdagent_default_dc',
}
//After the connection is successful, add a DataChannelListener
session.addHandle('onConnected', (data) => {
session.addDataChannelListener('wy_vdagent_default_dc', 'data', data => {
console.log('data from wy_vdagent_default_dc', data)
parseCommand(data)
});
});
function parseCommand(data) {
try {
// Remove the "data:" prefix
const jsonStr = data.replace(/^data:/, '').trim();
const json = JSON.parse(jsonStr);
if (json.action !== undefined) {
handleCommand(json.action, json);
} else if (json.cmd !== undefined) {
handleCommand(json.cmd, json);
} else {
console.warn("Invalid command format:", jsonStr);
}
} catch (e) {
console.error("Parsing failed:", data, e);
}
}
function handleCommand(cmd, json) {
try {
switch (cmd) {
case "authorizeCamera":
if (session != null) {
console.log(`setCameraCanUse true`);
session.setLocalConfig('setCameraCanUse', true);
}
break;
case "rotation":
const rotationValue = parseInt(json.value, 10);
break;
default:
break;
}
} catch (e) {
console.error("Command processing failed:", cmd, e);
}
}4. References
Is this page helpful?