我尝试实现android developer USB example code,我得到了NullPointerException
04-11 19:53:34.295:E / initial(11917):java.lang.NullPointerException
我的设备是NEXUS 7
这是我的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_host);
textView = (TextView)findViewById(R.id.textView1);
myThread = new Thread(this, "myThread Thread");
myThread.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
initial();
}
private void initial(){
try {
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
manager.requestPermission(device, mPermissionIntent);//the error came out at this line
while(deviceIterator.hasNext()){
device = deviceIterator.next();
Log.d("deviceIterator", device.toString());
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
textView.setText(device.toString());
}
});
}
} catch (Exception e) {
Log.e("initial", e.toString());
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
try {
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(TAG, "permission denied for device " + device);
}
}
}
} catch (Exception e) {
Log.e("onReceive", e.toString());
}
}
};
我做错了什么? 抱歉我的虚拟问题,这是我第一次使用USB功能