Nee*_*pta 6 usb android serial-communication
背景:我曾尝试在 stackoverflow、android 开发人员和网络上的各种其他资源方面寻求帮助。这是我最后的希望。我是通信新手,从 USB 的实现开始。以下是我的问题:
1) 当我将手机连接到 Windows PC 时,哪一个是主机?假设我想创建一个可以发送数据的应用程序,我是在做我的手机主机吗?
2) 对于这种情况(Windows PC 和 Android 手机),另一个是外围设备还是设备?他们一样吗?
3)从android开发者网站和关于USB的Windows论坛,我了解到需要遵循某些步骤,就像 - 创建USBManager的实例。- 创建获取设备列表 - 选择要从中建立连接的设备 - 创建接口 - 从该接口获取端点。- 创建 DeviceConnections 实例并调用 bulkTransfer 方法并发送数据。
但是当我尝试上述步骤时,我得到 device == null。我什至不知道我对上述通信方式的理解是否正确。
有人可以帮助我理解并建立 PC 和 android 手机之间的基本通信,并至少发送“hello world”。
非常感谢您阅读这么长的问题。
这是我所做的代码示例。这里 devicelist 返回 null。
public class MainActivity extends AppCompatActivity {
android.widget.Button usbButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomUSBManager cmanager = new CustomUSBManager();
//1) //Create instance of USB Manager using getSystemService
final UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
//2) //Create a list of devices
HashMap<String,UsbDevice> deviceList = manager.getDeviceList();
Log.d("Devicelist = ", String.valueOf(deviceList.get(0)));
//3) //Get a specific device from the list
//-----------------------------------------------------------------
Here is my manifest file.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.neeraj.usbcommunication1">
<uses-feature android:name="android.hardware.usb.host"></uses-feature>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
final UsbDevice device = deviceList.get(0); //getting first device
Run Code Online (Sandbox Code Playgroud)
这不会按您想要的方式工作。它UsbManager.getDeviceList()适用于带有 USB 端口的 Android 设备(例如平板电脑)。但是,您将充当设备的Android 设备连接到充当主机的PC 。
如果您想在 Android USB 设备和某些 USB 主机之间进行通信,您需要使用附件模式(https://developer.android.com/guide/topics/connectivity/usb/)。但这种模式需要 USB 主机端(即您的 PC)的特殊驱动程序支持。
另请注意,这getDeviceList()在配件模式下没有意义。这是因为连接的附件是 USB 主机,而不是 USB 设备。
在这篇文章中了解更多相关信息:Android 到 PC USB 读/写
请注意,我的答案基于此答案:https ://stackoverflow.com/a/14099963/5457878
| 归档时间: |
|
| 查看次数: |
8195 次 |
| 最近记录: |