USB host for android

帅比萌擦擦* 提交于 2019-12-23 12:17:16

问题


I am trying to communicate with my freeduino board which is similar to arduino uno via usb through android device 'nexus 7' which has 4.2 (jelly beans) in it.

I used the developers guide to communicate with the device from a couple of months but with no result. I think i am missing something minute in it. I am trying to simply display the vendor id of my freeduino board. My manifest file look like this.

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.usb_host_final_try.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
    </intent-filter>

    <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
        android:resource="@xml/device_filter" />
        </activity>
    </application>

</manifest>

I have created a file device_filter in res/xml dir. which look like this

 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <usb-device vendor-id="0403" product-id="07d7" />
</resources>

and my MainActivity.java has the following code.

package com.example.usb_host_final_try;

import java.util.HashMap;

import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        UsbDevice device = deviceList.get("deviceName");
        int vid=device.getVendorId();
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(Integer.toString(vid));
    }

please help me out i am screwed up over it from past few months now. I have tried doing this but it is also not working.

link

link

Stack overfolow question

stack overflow question

I have tried all these and still haven't been able to succeed. I also tried to use an if else loop to see if enumeration works where i set the text to device not found if no device is else settext to vendor id. On emulator is showed no device found but on my tablet wen i connect the device it force closes or else it still shows no device found wen nothing is connected.

The stack trace is here..

01-05 09:10:35.364: W/Trace(1658): Unexpected value from nativeGetEnabledTags: 0 01-05 09:10:35.364: W/Trace(1658): Unexpected value from nativeGetEnabledTags: 0 01-05 09:10:35.464: W/Trace(1658): Unexpected value from nativeGetEnabledTags: 0 01-05 09:10:35.464: W/Trace(1658): Unexpected value from nativeGetEnabledTags: 0 01-05 09:10:35.624: D/AndroidRuntime(1658): Shutting down VM 01-05 09:10:35.624: W/dalvikvm(1658): threadid=1: thread exiting with uncaught exception (group=0x40a70930) 01-05 09:10:35.644: E/AndroidRuntime(1658): FATAL EXCEPTION: main 01-05 09:10:35.644: E/AndroidRuntime(1658): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.usb_host_final_try/com.example.usb_host_final_try.MainActivity}: java.lang.NullPointerException 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.app.ActivityThread.access$600(ActivityThread.java:141) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.os.Handler.dispatchMessage(Handler.java:99) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.os.Looper.loop(Looper.java:137) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.app.ActivityThread.main(ActivityThread.java:5039) 01-05 09:10:35.644: E/AndroidRuntime(1658): at java.lang.reflect.Method.invokeNative(Native Method) 01-05 09:10:35.644: E/AndroidRuntime(1658): at java.lang.reflect.Method.invoke(Method.java:511) 01-05 09:10:35.644: E/AndroidRuntime(1658): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 01-05 09:10:35.644: E/AndroidRuntime(1658): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 01-05 09:10:35.644: E/AndroidRuntime(1658): at dalvik.system.NativeStart.main(Native Method) 01-05 09:10:35.644: E/AndroidRuntime(1658): Caused by: java.lang.NullPointerException 01-05 09:10:35.644: E/AndroidRuntime(1658): at com.example.usb_host_final_try.MainActivity.onCreate(MainActivity.java:35) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.app.Activity.performCreate(Activity.java:5104) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 01-05 09:10:35.644: E/AndroidRuntime(1658): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 01-05 09:10:35.644: E/AndroidRuntime(1658): ... 11 more 01-05 09:10:46.074: W/Trace(1712): Unexpected value from nativeGetEnabledTags: 0 01-05 09:10:46.074: W/Trace(1712): Unexpected value from nativeGetEnabledTags: 0 01-05 09:10:46.754: D/AndroidRuntime(1712): Shutting down VM 01-05 09:10:46.754: W/dalvikvm(1712): threadid=1: thread exiting with uncaught exception (group=0x40a70930) 01-05 09:10:46.766: E/AndroidRuntime(1712): FATAL EXCEPTION: main 01-05 09:10:46.766: E/AndroidRuntime(1712): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.usb_host_final_try/com.example.usb_host_final_try.MainActivity}: java.lang.NullPointerException 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.app.ActivityThread.access$600(ActivityThread.java:141) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.os.Handler.dispatchMessage(Handler.java:99) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.os.Looper.loop(Looper.java:137) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.app.ActivityThread.main(ActivityThread.java:5039) 01-05 09:10:46.766: E/AndroidRuntime(1712): at java.lang.reflect.Method.invokeNative(Native Method) 01-05 09:10:46.766: E/AndroidRuntime(1712): at java.lang.reflect.Method.invoke(Method.java:511) 01-05 09:10:46.766: E/AndroidRuntime(1712): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 01-05 09:10:46.766: E/AndroidRuntime(1712): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 01-05 09:10:46.766: E/AndroidRuntime(1712): at dalvik.system.NativeStart.main(Native Method) 01-05 09:10:46.766: E/AndroidRuntime(1712): Caused by: java.lang.NullPointerException 01-05 09:10:46.766: E/AndroidRuntime(1712): at com.example.usb_host_final_try.MainActivity.onCreate(MainActivity.java:35) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.app.Activity.performCreate(Activity.java:5104) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 01-05 09:10:46.766: E/AndroidRuntime(1712): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 01-05 09:10:46.766: E/AndroidRuntime(1712): ... 11 more 01-05 09:10:49.104: I/Process(1712): Sending signal. PID: 1712 SIG: 9


回答1:


EDIT: Permissions aren't actually needed if defined in XML, so the answer below does not apply. The issue was an NPE - no such device "deviceName" existed in the code.


It looks like you are not obtaining permission to use the USB accessory, as described here in the docs and in this answer.

In your onCreate():

UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
private static final String ACTION_USB_PERMISSION =
    "com.android.example.USB_PERMISSION";
...
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);

In your Activity:

private static final String ACTION_USB_PERMISSION =
    "com.android.example.USB_PERMISSION";
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) {
                UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);

                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if(accessory != null){
                        //call method to set up accessory communication
                    }
                }
                else {
                    Log.d(TAG, "permission denied for accessory " + accessory);
                }
            }
        }
    }
};

To show the dialog to get permission:

UsbAccessory accessory;
...
mUsbManager.requestPermission(accessory, mPermissionIntent);



回答2:


the main activity will now become like this and rest of it remains the same

    package com.example.usb_host_final_try;

import java.util.HashMap;
import java.util.Iterator;

import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
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.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    protected static final String TAG = null;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while(deviceIterator.hasNext()){
            UsbDevice device = deviceIterator.next();
            String s=device.getDeviceName();
            int pid= device.getProductId();
            int vid = device.getVendorId();
            TextView tv = (TextView) findViewById(R.id.textview);
            tv.setText(s+"\n"+Integer.toString(pid)+"\n"+Integer.toString(vid));
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

All thanks to oleg Vaskevich!!



来源:https://stackoverflow.com/questions/14168947/usb-host-for-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!