1
我想在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());
初始化'usbCom = new Usb_Communciation(this,getIntent());'in'onCreate()'方法。在聲明部分只聲明變量'Usb_Communciation usbCom;' – Piyush
仍然是崩潰 –