我正在尝试使用输入输出流与android上的USB通信,使用构造函数如果我单独使用处理程序它没有任何问题进行通信,但是如果我使用常见的构造函数它会崩溃应用程序说空指针异常希望我是做一些错误的错误,但不知道我在哪里犯了错误
和代码如下
public class BasicAccessoryDemo extends Activity implements View.OnClickListener {
Usb_Communciation usbCom = new Usb_Communciation(this, getIntent());
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mycontrol, close_command;
mycontrol = (Button) findViewById(R.id.send_command);
mycontrol.setOnClickListener(this);
close_command = (Button) findViewById(R.id.close_command);
close_command.setOnClickListener(this);
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_command:
byte[] commandPacket = new byte[2];
commandPacket[0] =0x12;
commandPacket[1] =0x34;
usbCom.Send_message(commandPacket);
break;
case R.id.close_command:
byte[] commandPackets = new byte[2];
commandPackets[0] = 0;
commandPackets[1] = 0;
usbCom.Send_message(commandPackets);
break;
}
}
}
和沟通课
public class Usb_Communciation {
public final static int USBAccessoryWhat = 0;
public int firmwareProtocol = 0;
public static USBAccessoryManager accessoryManager;
public static String TAG = "MICROCHIP";
public static final int APP_CONNECT = (int) 0xAE;
public boolean deviceAttached = false;
public Usb_Communciation(Context mContext, Intent intent) {
accessoryManager = new USBAccessoryManager(handler, USBAccessoryWhat);
accessoryManager.enable(mContext, intent);
}
public void Send_message(byte[] data) {
try {
accessoryManager.write(data);
} catch (Exception e) {
Log.d(TAG,
"USBAccessoryManager:write():IOException: arasu "
+ e.toString());
e.printStackTrace();
}
}
public Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
byte[] commandPacket = new byte[64];
byte[] WriteValue = new byte[2];
switch (msg.what) {
//Something inside
} //switch
} //handleMessage
}; //handler
public int getFirmwareProtocol(String version) {
String major = "0";
int positionOfDot;
positionOfDot = version.indexOf('.');
if (positionOfDot != -1) {
major = version.substring(0, positionOfDot);
}
return new Integer(major).intValue();
}
}
和USB配件管理器类的启用方法
public RETURN_CODES enable(Context context, Intent intent) {
//something inside
}
,错误显示在活动部分和usb_Communcation类上的相同构造函数
Usb_Communciation usbCom = new Usb_Communciation(this, getIntent());
答案 0 :(得分:1)
试试这个:
Usb_Communciation usbCom;
@Override
public void onCreate(Bundle savedInstanceState) {
usbCom = new Usb_Communciation(this, getIntent());
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mycontrol, close_command;
mycontrol = (Button) findViewById(R.id.send_command);
mycontrol.setOnClickListener(this);
close_command = (Button) findViewById(R.id.close_command);
close_command.setOnClickListener(this);
}