Android USB 通信(Socket 详解)

来源:互联网 发布:千兆网络用什么网线 编辑:程序博客网 时间:2024/06/12 21:22

前言:
昨个帮同事忙, 应下了一个Android 与PC端通信的Demo,遂今早上折腾了一会,也算是写出来了,而且发现了一个比较严重的问题:参考资料都是12年,13年的,很多的Sample 都是不能用的, 所以打算更新一下。


Android Code

首先是清单文件中的权限:

    <uses-permission android:name="android.hardware.usb.host" />    <uses-permission android:name="android.hardware.usb.accessory" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    // 第一个与第二个是必要的, 第三个由于此项目需要,所以也就没再去除。

然后注册一个广播接收器

public class ServiceBroadcastReceiver extends BroadcastReceiver {    private static String START_ACTION = "NotifyServiceStart";    private static String STOP_ACTION = "NotifyServiceStop";    @Override    public void onReceive(Context context, Intent intent) {        Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"                  + "ServiceBroadcastReceiver onReceive");          String action = intent.getAction();          if (START_ACTION.equalsIgnoreCase(action)) {              context.startService(new Intent(context, androidService.class));              Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"                      + "ServiceBroadcastReceiver onReceive start end");          } else if (STOP_ACTION.equalsIgnoreCase(action)) {              context.stopService(new Intent(context, androidService.class));              Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"                      + "ServiceBroadcastReceiver onReceive stop end");          }      }}

当然, 也不要忘记在清单文件中去注册;

  <receiver android:name=".ServiceBroadcastReceiver">            <intent-filter >                <action android:name="NotifyServiceStart"/>                <action android:name="NotifyServiceStop" />            </intent-filter>        </receiver>//其中,两个action 是我们过滤的条件,诸位看名字也应该明白。

emmmmm…. 不想写了,你们直接去GitHub 拿代码吧, 不懂的就发邮件或者加QQ问我;

QQ 7641436; 

Sample 地址

阅读全文
1 0
原创粉丝点击