android - 如何在启用 LockTask 模式的 Android 应用程序中获得与 USB 闪存驱动器通信的运行时权限?

标签 android android-permissions android-9.0-pie runtime-permissions usb-otg

我正在为一次性设备开发具有 LockTask 模式的应用程序 SDK 28。该应用程序通过 USB OTG 将一些文件从设备传输到 USB 闪存驱动器。对于与闪存驱动器的通信,应用程序请求运行时权限,但 LockTask 模式会阻止对话消息以接受用户权限。因此,应用程序无法获得权限,并且当它想要传输文件时失败。我想知道是否退出了在锁定任务模式下启用某些权限或启用这些对话的方法?

请求与闪存驱动器通信的权限

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void check() {
    manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    /*
     * this block required if you need to communicate to USB devices it's
     * take permission to device
     * if you want than you can set this to which device you want to communicate
     */
    // ------------------------------------------------------------------
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);
    // -------------------------------------------------------------------
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    String i = "";
    while (deviceIterator.hasNext()) {
        device = deviceIterator.next();
        manager.requestPermission(device, mPermissionIntent);
        i +=  "USB Detectada!!";
    }
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        if (ACTION_USB_PERMISSION.equals(action)) {
            // Permission requested
            synchronized (this) {
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    //cueMsg.cueCorrect("Permiso otorgado");
                    // User has granted permission
                    // ... Setup your UsbDeviceConnection via mUsbManager.openDevice(usbDevice) ...
                } else {
                    cueMsg.cueError("Permiso denegado");
                    // User has denied permission
                }
            }
        }
        if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            cueMsg.cueError("Usb desconectado");
            // Device removed
            synchronized (this) {
                // ... Check to see if usbDevice is yours and cleanup ...
            }
        }
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            cueMsg.cueCorrect("Usb conectado");
            // Device attached
        }
    }
};

LockTask 模式代码

@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onStart() {
    if (mDevicePolicyManager.isLockTaskPermitted(this.getPackageName())){
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_NONE){
            setDefaultCosuPolicies(true);
            startLockTask();
        }
    }
    super.onStart();
}

@RequiresApi(api = Build.VERSION_CODES.M)
private void unlockApp(){
    ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
    if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED){
        stopLockTask();
    }
    setDefaultCosuPolicies(false);
}


@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void setDefaultCosuPolicies(boolean active) {
    //Configuración de restricciones de usuario
    setUserRestriction(UserManager.DISALLOW_SAFE_BOOT, active);
    setUserRestriction(UserManager.DISALLOW_FACTORY_RESET, active);
    setUserRestriction(UserManager.DISALLOW_ADD_USER, active);

    //setUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, active);
    setUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER, false);


    setUserRestriction(UsbManager.EXTRA_PERMISSION_GRANTED, true);
    setUserRestriction(UserManager.DISALLOW_ADJUST_VOLUME, active);


    //Desabilitar lockscreen y barra de estado
    mDevicePolicyManager.setKeyguardDisabled(mAdminComponentName, active);
    mDevicePolicyManager.setStatusBarDisabled(mAdminComponentName, active);
    //Permisos para USB
    mDevicePolicyManager.setPermissionGrantState(mAdminComponentName,
            "com.example.devicepolicymanager2",
            UsbManager.EXTRA_PERMISSION_GRANTED,
            DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);

    //Habilitar Plugged in
    enableStayOnWhilePluggedIn(active);

    //Configurar politicas de actualización de sistema
    if (active){
        mDevicePolicyManager.setSystemUpdatePolicy(mAdminComponentName, SystemUpdatePolicy.createWindowedInstallPolicy(60, 120));
    } else {
        mDevicePolicyManager.setSystemUpdatePolicy(mAdminComponentName, null);
    }

    //Configurar la actividad como un paquete lock task
    //mDevicePolicyManager.setLockTaskPackages(mAdminComponentName,
    //      active ? new String[]{getPackageName()} : new String[]{});
    mDevicePolicyManager.setLockTaskPackages(mAdminComponentName, APP_PACKAGES);


    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MAIN);
    intentFilter.addCategory(Intent.CATEGORY_HOME);
    intentFilter.addCategory(Intent.CATEGORY_DEFAULT);

    if (active){
        //configura actividad cosu como home para que comience al reiniciarse
        mDevicePolicyManager.addPersistentPreferredActivity(mAdminComponentName,
                intentFilter,
                new ComponentName(getPackageName(),
                        LoginActivity.class.getName()));
    } else {
        mDevicePolicyManager.clearPackagePersistentPreferredActivities(mAdminComponentName, getPackageName());
    }
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void setUserRestriction(String restriction, boolean disallow){
    if (disallow){
        mDevicePolicyManager.addUserRestriction(mAdminComponentName, restriction);
    }else {
        mDevicePolicyManager.clearUserRestriction(mAdminComponentName, restriction);
    }
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void enableStayOnWhilePluggedIn(boolean enabled){
    if (enabled){
        mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
                Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
                Integer.toString(BatteryManager.BATTERY_PLUGGED_AC |
                        BatteryManager.BATTERY_PLUGGED_USB |
                        BatteryManager.BATTERY_PLUGGED_WIRELESS));
    }else {
        mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
                Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
                "0");
    }
}

最佳答案

在锁定任务模式期间,不允许打开任何未列入白名单的应用程序。您必须将 USB 对话框应用程序列入白名单。

    private static String USB_DIALOG_PACKAGE = "com.android.systemui";

    private static String[] APP_PACKAGES = {[YOUR OTHER WHITE LISTED PACKAGES HERE],USB_DIALOG_PACKAGE };

关于android - 如何在启用 LockTask 模式的 Android 应用程序中获得与 USB 闪存驱动器通信的运行时权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55343923/

相关文章:

android - 如何更改 Android 菜单项的自定义字体?

java - 使用 ViewModel 设置数据后,EditText.getText().toString() 在 onCreate() 处为空

java - GPS 定位精度问题

android - 执行需要粗略位置许可的网络扫描

android - getAppStandbyBucket 需要未知权限

java - 如何从数组中确定和使用给定数量的问题?安卓工作室

android - 如何从 codename1 应用程序中删除 "permission required"

android - 权限被拒绝 - 缺少 INTERNET 权限?

java - 我的应用程序在 android 9 版本中不断崩溃,抛出 java.lang.SecurityException

安卓 P - 警告 : "incompatible version of the Android OS"