Android USB自动授予权限

时间:2012-11-30 14:54:35

标签: android

是否有访问IUsbManager接口类来调用service.grantDevicePermission()方法来自动设置USB设备的权限而不总是让ConfirmationActivity显示询问用户?

由于

3 个答案:

答案 0 :(得分:2)

当然是的!你可以使用这段代码,为我工作:

public boolean grantAutomaticPermission(UsbDevice usbDevice)
 {
    try
    {
     Context context=YourActivityOrApplication;
     PackageManager pkgManager=context.getPackageManager();
     ApplicationInfo     appInfo=pkgManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);

     Class serviceManagerClass=Class.forName("android.os.ServiceManager");
     Method getServiceMethod=serviceManagerClass.getDeclaredMethod("getService",String.class);
     getServiceMethod.setAccessible(true);
     android.os.IBinder binder=(android.os.IBinder)getServiceMethod.invoke(null, Context.USB_SERVICE);

     Class iUsbManagerClass=Class.forName("android.hardware.usb.IUsbManager");
     Class stubClass=Class.forName("android.hardware.usb.IUsbManager$Stub");
     Method asInterfaceMethod=stubClass.getDeclaredMethod("asInterface", android.os.IBinder.class);
     asInterfaceMethod.setAccessible(true);
     Object iUsbManager=asInterfaceMethod.invoke(null, binder);


     System.out.println("UID : " + appInfo.uid + " " + appInfo.processName + " " + appInfo.permission);
     final Method grantDevicePermissionMethod = iUsbManagerClass.getDeclaredMethod("grantDevicePermission", UsbDevice.class,int.class);
     grantDevicePermissionMethod.setAccessible(true);
     grantDevicePermissionMethod.invoke(iUsbManager, usbDevice,appInfo.uid);


     System.out.println("Method OK : " + binder + "  " + iUsbManager);
     return true;
    }
    catch(Exception e)
    {
     System.err.println("Error trying to assing automatic usb permission : ");
     e.printStackTrace();
     return false;
    }
 }

我所做的是使用反射实现android的方式。要使用此代码,您必须具有:

<uses-permission android:name="android.permission.MANAGE_USB"/>

然而,有一个问题,我完全不知道,如果我错了,请更正我:USER拥有权限,而不是应用程序,那么如果您尝试从应用程序仪表板启动应用程序,您将失败。有必要确保比android开始你的应用程序,例如,将其设置为启动器并让它以HOME意图开始。

问候,期待可以帮助别人。

答案 1 :(得分:2)

是的,你可以,

如果您使用@CristhianB发布的代码,您将能够完成它但是这是一个地狱但是您将需要使用以下其中一个:

  1. 将您的应用移至priv-app文件夹,并将权限设置为以系统应用程序身份运行。 (使用userId和用户组)
  2. 和@CristhianB一样做(设置应用程序作为系统服务运行,实际上将其设置为作为启动器运行。
  3. 用你的密钥重新签名Os,然后在你的应用程序清单android:protectionLevel =“signatureOrSystem”中设置权限属性,你的金色!
  4. 第三种方法允许您的应用程序执行您想要的任何操作,因为它将使用与系统键相同的键进行签名,这意味着您作为系统应用程序运行,但您不必在priv-app文件夹中安装您的应用程序。

    如果您对此事有任何疑问,我会很乐意提供帮助,我刚刚实施了同样的事情,我花了三个星期才完成它所以我可以为您节省大量时间。 :-)

答案 2 :(得分:0)

当然不是。这将首先使权限无效。但是用户可以选择始终允许特定连接。