用Android代码实现自动打开USB调试

打开Android手机的USB调试对于使用豌豆夹、调试程序等来说很重要。下面说说如何用代码自动打开USB调试。先分析USB调试的相关源代码。

在 packages/apps/Settings/src/com/android/settings/DevelopmentSettings.java 找到关于 USB Debug Enable 的代码:

[java]  view plain copy
  1. Settings.Secure.putInt(getContentResolver(), Settings.Secure.ADB_ENABLED,  0 );    

此文件中,将根据用户设置将其值保存到 Settings 数据库中。别处将根据其值动态变化做出相应动作

经搜索,在 frameworks/base/services/java/com/android/server/NotificationManagerService.java 中存在利用该值判断是否在状态栏中进行通知。代码如下:


别处将根据其值动态变化做出相应动作如状态栏消息提示。


[java]  view plain copy
  1. void  observe() {    
  2.     ContentResolver resolver = mContext.getContentResolver();    
  3.     resolver.registerContentObserver(Settings.Secure.getUriFor(    
  4.             Settings.Secure.ADB_ENABLED), false ,  this );    
  5.     update();    
  6. }    
  7.     
  8. @Override   public   void  onChange( boolean  selfChange) {    
  9.     update();    
  10. }    
  11.     
  12. public   void  update() {    
  13.     ContentResolver resolver = mContext.getContentResolver();    
  14.     mAdbEnabled = Settings.Secure.getInt(resolver,    
  15.                 Settings.Secure.ADB_ENABLED, 0 ) !=  0 ;    
  16.     updateAdbNotification();    
  17. }    

 


通过分析代码,我们可以实现用程序自动打开usb调试了。

[java]  view plain copy
  1. boolean enableAdb = (Settings.Secure.getInt(getContentResolver(), Settings.Secure.ADB_ENABLED, 0) > 0);  
  2.     if (!enableAdb) {  
  3.     Settings.Secure.putInt(getContentResolver(), Settings.Secure.ADB_ENABLED, 1);  
  4.     }  


马上进行运行,会出现异常,通过Logcat可以看到没有权限。android.permission.WRITE_SECURE_SETTINGS是不允许普通程序来执行,必须要有系统的签名或放到

/system/app下。

(1)、在AndroidManifest.xml加上两个权限

[html]  view plain copy
  1. <uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>   
  2. <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />  

 

可以把程序push到/system/app,并对这个apk加上0644的权限,重启手机,可以发现usb调试自动打开了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值