使用线程和 USB 连接后应用程序屏幕空白

Blank app screen after using threads and USB connection

我是 Android 的初学者。我试图开发一个基本的应用程序来通过 USB 连接进行通信。我必须等待传入的数据,因为我真的不知道它是哪一刻到来的,所以我用 while(true) 解决了它。对于这个 while 循环,我尝试使用 Thread。我对线程没有太多经验。

但问题是,现在每次按下我的 phone 上的后退按钮,然后我尝试再次打开我的应用程序,它只显示一个空白的应用程序屏幕。

你能帮帮我吗?谢谢

主要活动class:

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 向我显示以下消息:

此处理程序 class 应该是静态的,否则可能会发生泄漏 (null)

如果没有 运行 代码,我会发现很难确定确切的问题,但这里有一些可能有帮助的提示。

首先在您的 activity 停止后调用 onRestart(),然后再重新启动它,当 activity 开始与用户交互时调用 onResume()。在这两种情况下,r 可能没有值,因为 A 按钮未被按下或 B class 被卸载以释放内存。