我是Android的初学者。我正在尝试开发一个基本的应用程序,通过USB连接进行通信。我必须等待传入的数据,因为我真的不知道它到哪一刻,所以我用 while(true)解决了这个问题。对于这个while循环,我尝试使用Thread。我对Threads没有多少经验。
但问题是,现在每次按下手机上的后退按钮,之后我再次尝试打开我的应用程序,它只显示一个空白的应用程序屏幕。
你能帮帮我吗?感谢。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);
}
}
}
}
};
}
修改
现在我意识到,一两分钟后,按钮和TextView会出现在屏幕上。 我不知道它是否有帮助,但Android Studio会向我显示以下消息:
此Handler类应为静态或可能发生泄漏(null)
答案 0 :(得分:1)
我会发现很难在不运行代码的情况下识别确切的问题,但这里有一些可能有帮助的指针。
首先,在您的活动停止之后,再次启动活动之前调用onRestart(),并在活动开始与用户交互时调用onResume()。在这两种情况下,r可能没有值,因为没有按下A按钮或B已卸载类以释放内存。