简体   繁体   English

Android USB Host示例在Android Studio中不起作用

[英]Android USB Host example not working in Android Studio

I have found the following example at http://mobilemerit.com/android-app-for-usb-host-with-source-code/# . 我在http://mobilemerit.com/android-app-for-usb-host-with-source-code/#找到了以下示例。 This code is meant to list connected USB devices but it does not compile in Android Studio. 该代码旨在列出已连接的USB设备,但无法在Android Studio中进行编译。 I'm wondering what is necessary in order for it to compile and run? 我想知道什么才能使其编译和运行?

activity_main.xml activity_main.xml

 <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" > <button android:id="@+id/check" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Check USB devices"></button> <textview android:id="@+id/info" android:layout_width="match_parent" android:layout_height="wrap_content"></textview> </linearlayout> 

MainActivity.java MainActivity.java

 package com.mobilemerit.usbhost; import java.util.HashMap; import java.util.Iterator; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.mobilemerit.usbhost.R; public class MainActivity extends Activity { PendingIntent mPermissionIntent; Button btnCheck; TextView textInfo; UsbDevice device; UsbManager manager; private static final String ACTION_USB_PERMISSION = "com.mobilemerit.usbhost.USB_PERMISSION"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnCheck = (Button) findViewById(R.id.check); textInfo = (TextView) findViewById(R.id.info); btnCheck.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { textInfo.setText(""); checkInfo(); } }); } private void checkInfo() { 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 += "\\n" + "DeviceID: " + device.getDeviceId() + "\\n" + "DeviceName: " + device.getDeviceName() + "\\n" + "DeviceClass: " + device.getDeviceClass() + " - " + "DeviceSubClass: " + device.getDeviceSubclass() + "\\n" + "VendorID: " + device.getVendorId() + "\\n" + "ProductID: " + device.getProductId() + "\\n"; } textInfo.setText(i); } private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbDevice device = (UsbDevice) intent .getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra( UsbManager.EXTRA_PERMISSION_GRANTED, false)) { if (device != null) { // call method to set up device communication } } else { Log.d("ERROR", "permission denied for device " + device); } } } } }; } 

Manfest.xml Manfest.xml

 < ?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.mobilemerit.usbhost" android:versionCode="1" android:versionName="1.0" > <uses -feature android:name="android.hardware.usb.host"></uses> <uses -sdk android:minSdkVersion="12" android:targetSdkVersion="19"></uses> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.mobilemerit.usbhost.MainActivity" android:label="@string/app_name" > <intent -filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER"></category> </intent> </activity> </application> </manifest> 

In Android Studio you can choose "Import Project" and select the folder that the USB example files are placed. 在Android Studio中,您可以选择“导入项目”,然后选择放置USB示例文件的文件夹。 Select the top level folder. 选择顶级文件夹。 After that Android Studio will build you the project. 之后,Android Studio将为您构建项目。 If you encounter errors or Android Studio needs to download files you should let it do that. 如果遇到错误或Android Studio需要下载文件,则应让其执行。 Then click the menu: Build -> Rebuild Project. 然后单击菜单:生成->重建项目。 All done! 全部做完!

Here's the file built and ready to run: Working AS USB example Courtesy of mobilemerit. 这是已构建并可以运行的文件: AS USB示例工作该示例由mobilemerit提供。

Here's a screenshot takes from Android Studio while the app is running on my Samsung Note 3: Picture of USB example running on Note 3 这是该应用程序在我的Samsung上运行时Android Studio的屏幕截图。Note 3: 在Note 3上运行的USB示例图片

PS. PS。 I am in no way affiliated with mobilemerit. 我绝不隶属于mobilemerit。

I have Android Studio version 1.3. 我有Android Studio版本1.3。 I have corrected the differences for 1.3. 我更正了1.3的差异。 Make sure for Application Name you type: 确保输入的应用程序名称为:

usbhost USB主机

For company name type: 对于公司名称,请输入:

mobilemerit.com mobilemerit.com

This will give you the correct package name. 这将为您提供正确的软件包名称。 My emulator can not detect USB devices. 我的仿真器无法检测到USB设备。 So, I used my phone and connected a USB device to it. 因此,我使用了手机并将USB设备连接到它。

activity_main.xml activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingBottom="@dimen/activity_vertical_margin"
              android:paddingLeft="@dimen/activity_horizontal_margin"
              android:paddingRight="@dimen/activity_horizontal_margin"
              android:paddingTop="@dimen/activity_vertical_margin"
              android:orientation="vertical"
              tools:context=".MainActivity" >

    <Button android:id="@+id/check"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Check USB devices" />

    <TextView android:id="@+id/info"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity.java MainActivity.java

package com.mobilemerit.usbhost;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.mobilemerit.usbhost.R;

public class MainActivity extends Activity {
    PendingIntent mPermissionIntent;
    Button btnCheck;
    TextView textInfo;
    UsbDevice device;
    UsbManager manager;
    private static final String ACTION_USB_PERMISSION = "com.mobilemerit.usbhost.USB_PERMISSION";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCheck = (Button) findViewById(R.id.check);
        textInfo = (TextView) findViewById(R.id.info);
        btnCheck.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                textInfo.setText("");
                checkInfo();
            }
        });

    }

    private void checkInfo() {
        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 += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
                    + "DeviceName: " + device.getDeviceName() + "\n"
                    + "DeviceClass: " + device.getDeviceClass() + " - "
                    + "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
                    + "VendorID: " + device.getVendorId() + "\n"
                    + "ProductID: " + device.getProductId() + "\n";
        }

        textInfo.setText(i);
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice) intent
                            .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(
                            UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            // call method to set up device communication
                        }
                    } else {
                        Log.d("ERROR", "permission denied for device " + device);
                    }
                }
            }
        }
    };
}

AndroidManifest.xml AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.mobilemerit.usbhost"
          android:versionCode="1"
          android:versionName="1.0" >

<uses-feature android:name="android.hardware.usb.host"/>
<uses-sdk
    android:minSdkVersion="12"
    android:targetSdkVersion="19"/>

    <application android:allowBackup="true"
                 android:icon="@mipmap/ic_launcher"
                 android:label="@string/app_name"
                 android:theme="@style/AppTheme" >
        <activity android:name="com.mobilemerit.usbhost.MainActivity"
                  android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM