1
我是Android的初学者。我试图开发一个基本的应用程序来通过USB连接进行通信。我必须等待传入的数据,因为我不知道它到了哪一刻,所以我用解决了它,而(真)。对于这个while循环,我尝试使用Thread。我没有太多的线程经验。使用线程和USB连接后的空白应用程序屏幕
但问题是,现在每次按下手机上的后退按钮,然后我尝试再次打开我的应用程序,它只显示一个空白的应用程序屏幕。
请问您能帮我吗?谢谢。
MainActivity类别:
public class MainActivity extends AppCompatActivity {
UsbDevice device;
Button bShow;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
UsbManager mUsbManager;
PendingIntent mPermissionIntent;
TextView tvTest, tvAppend;
String sendText = "@V\r\n";
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
int controlTransferResult;
byte[] readBytes = new byte[128];
//byte[] data = new byte[4096];
UsbEndpoint epOut = null, epIn = null;
UsbDeviceConnection connection;
int recvBytes;
String readString = "";
Thread thread;
Runnable r;
UsbInterface intf;
Handler handler= new Handler(){
@Override
public void handleMessage(Message msg) {
tvAppend.append(readString);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTest = (TextView) findViewById(R.id.textView);
tvAppend = (TextView) findViewById(R.id.textView2);
bShow= (Button)findViewById(R.id.button);
showData();
}
@Override
public void onPause() {
super.onPause(); // Always call the superclass method first
thread.interrupt();
}
@Override
protected void onStop() {
super.onStop();
thread.interrupt();
}
@Override
protected void onResume() {
super.onResume();
thread = new Thread(r);
thread.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
thread.interrupt();
}
@Override
protected void onRestart() {
super.onRestart();
thread = new Thread(r);
thread.start();
}
public void showData(){
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
if(deviceList.toString().equals("{}")){
Toast.makeText(MainActivity.this,"No USB device found!", Toast.LENGTH_SHORT).show();
return;
}else{
tvTest.setText(deviceList.toString());
}
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
device = deviceIterator.next();
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
mUsbManager.requestPermission(device, mPermissionIntent);
bShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
r = new Runnable() {
@Override
public void run() {
synchronized (this) {
while (true) {
Arrays.fill(readBytes, (byte) 0);
recvBytes = connection.bulkTransfer(epIn, readBytes, readBytes.length, 0);
if (recvBytes != 2) {
readString = new String(readBytes);
readString = readString.replace("\u0001`","");
handler.sendEmptyMessage(0);
}
}
}
}
};
thread = new Thread(r);
thread.start();
}
});
}
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
intf = device.getInterface(0);
// look for our bulk endpoints
for (int i = 0; i < intf.getEndpointCount(); i++) {
UsbEndpoint ep = intf.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
epOut = ep;
} else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
epIn = ep;
}
}
}
if (epOut == null || epIn == null) {
throw new IllegalArgumentException("Not all endpoints found.");
}
connection = mUsbManager.openDevice(device);
connection.claimInterface(intf, forceClaim);
bytes = sendText.getBytes();
tvAppend.setText("a" + bytes.length);
connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
connection.controlTransfer(0x40, 0, 1, 0, null, 0, 0);// clear Rx
connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
controlTransferResult = connection.controlTransfer(0x40, 0x03, 0x4138, 0, null, 0, 0);
ByteBuffer buffer = ByteBuffer.allocate(bytes.length+1);
UsbRequest request = new UsbRequest();
buffer.put(bytes);
request.initialize(connection, epOut);
request.queue(buffer, bytes.length);
}
}
else {
Log.d("MyActivity", "permission denied for device " + device);
}
}
}
}
};
}
编辑:
现在我意识到,一两分钟后,按钮和TextViews出现在屏幕上。 我不知道是否有帮助,但Android Studio中显示我以下消息:
这个处理程序类应该是静态的或可能发生泄漏(空)
我认为,它应该是内存问题,因为在几分钟后,按钮和TextViews出现在屏幕上,并在应用程序停止一段时间后出现。另外我的Android Studio向我显示一条消息:这个Handler类应该是静态的或者可能发生泄漏(null)你有什么建议?我怎么能解决这个问题? – adamhala007
您正在使用处理程序写入屏幕,Android为此提供了一种方法。 。 getActivity()runOnUiThread(新的Runnable(){ @Override 公共无效的run(){ tvAppend.append( “一些字符串”);} }); 也看看这个问题和[答案](http://stackoverflow.com/a/10644656/4984266)你需要在你的while循环内停止条件,你可能想在迭代之间的Thread.sleep。 – harveytoro
runOnUiThread莫名其妙地没有奏效,但似乎Thread.sleep解决了这个问题。谢谢 :) – adamhala007