adamhala007
adamhala007

Reputation: 723

Blank app screen after using threads and USB connection

I am beginner in Android. I was trying to develop a basic app to communicate via USB connection. I have to wait for the incoming data, because I don't really know, which moment it comes, so I solved it with while(true). For this while loop I tried to use Thread. I do not have much experience with Threads.

But the problem is, that now every time a push the back button on my phone and after that I try to open once again my app, it shows just a blank app screen.

Could you help me please? Thanks.

MainActivity 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);
                }
            }
        }
    }
};


}

EDIT:

Now I realized, that after a minute or two the button and the TextViews appear on the screen. I don't know if it helps, but Android Studio displays me the following message:

This Handler class should be static or leaks might occur (null)

Upvotes: 1

Views: 120

Answers (1)

harveytoro
harveytoro

Reputation: 132

I would find it difficult to identify the exact issue without running the code but here are some pointers that may help.

Firstly onRestart() is called after your activity has been stopped, prior to it being started again and onResume() is called when the activity will start interacting with the user. In both cases r may not have a value because the A the button hasn't been pressed or B the class was unloaded to free up memory.

Upvotes: 1

Related Questions