Java 如何增加处理程序中的缓冲区大小?

Java 如何增加处理程序中的缓冲区大小?,java,android,arduino,buffer,Java,Android,Arduino,Buffer,我正在android应用程序上绘制图形。 我想使用大小等于512的缓冲区来存储来自arduino的传入数据。缓冲区满后,将绘制图形并继续运行。 如何更改代码以实现这一点 Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(m

我正在android应用程序上绘制图形。 我想使用大小等于512的缓冲区来存储来自arduino的传入数据。缓冲区满后,将绘制图形并继续运行。 如何更改代码以实现这一点

Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        switch(msg.what){
        case Bluetooth.SUCCESS_CONNECT:
            Bluetooth.connectedThread = new Bluetooth.ConnectedThread((BluetoothSocket)msg.obj);
            Toast.makeText(getApplicationContext(), "Connected!", 0).show();
            String s = "successfully connected";
            Bluetooth.connectedThread.start();
            break;
        case Bluetooth.MESSAGE_READ:

            byte[] readBuf = (byte[]) msg.obj;
            String strIncom = new String(readBuf, 0, 5);                 // create string from bytes array

            Log.d("strIncom", strIncom);
            if (strIncom.indexOf('.')==2 && strIncom.indexOf('s')==0){
                strIncom = strIncom.replace("s", "");
                if (isFloatNumber(strIncom)){
                    Series.appendData(new GraphViewData(graph2LastXValue,Double.parseDouble(strIncom)),AutoScrollX);

                    //X-axis control
                    if (graph2LastXValue >= Xview && Lock == true){
                        Series.resetData(new GraphViewData[] {});
                        graph2LastXValue = 0;
                    }else graph2LastXValue += 0.1;

                    if(Lock == true)
                        graphView.setViewPort(0, Xview);
                    else
                        graphView.setViewPort(graph2LastXValue-Xview, Xview);

                    //refresh
                    GraphView.removeView(graphView);
                    GraphView.addView(graphView);

                }
            }

            break;
        }
    }

    public boolean isFloatNumber(String num){
        //Log.d("checkfloatNum", num);
        try{
            Double.parseDouble(num);
        } catch(NumberFormatException nfe) {
            return false;
        }
        return true;
    }

};
这是我的蓝牙代码:

public class Bluetooth extends Activity implements OnItemClickListener{

public static void disconnect(){
    if (connectedThread != null) {
        connectedThread.cancel(); 
        connectedThread = null;
    }
}

public static void gethandler(Handler handler){//Bluetooth handler
    mHandler = handler;
}
static Handler mHandler = new Handler();

static ConnectedThread connectedThread;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);
    init();
    if (btAdapter==null){
        Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
        finish();
    }else{
        if (!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }

}


private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBT() {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    devicesArray = btAdapter.getBondedDevices();
    if (devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());
        }
    }
}

private void init(){
    listView = (ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>(); 
    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int a=0;a<pairedDevices.size();a++){
                    if (device.getName().equals(pairedDevices.get(a))){
                        //append
                        s = "(Paired)";
                        break;
                    }
                }
                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());

            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if (btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }  
        }

    };

    registerReceiver(receiver, filter);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
        finish();
    }
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    if (btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if (listAdapter.getItem(arg2).contains("(Paired)")){

        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
    }else {
        Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
    }
}

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        btAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
            //connectedThread = new ConnectedThread(mmSocket);
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

static class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
    StringBuffer sbb = new StringBuffer();
    public void run() {

        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                buffer = new byte[1024];
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String income) {

        try {
            mmOutStream.write(income.getBytes());
            for(int i=0;i<income.getBytes().length;i++)
            Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
公共类Bluetooth extends活动实现了McClickListener{
公共静态无效断开连接(){
if(connectedThread!=null){
connectedThread.cancel();
connectedThread=null;
}
}
公共静态void gethandler(处理程序处理程序){//Bluetooth处理程序
mHandler=handler;
}
静态处理程序mHandler=新处理程序();
静态ConnectedThread ConnectedThread;
公共静态最终UUID MY_UUID=UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
受保护的静态最终int成功连接=0;
受保护的静态最终int消息_READ=1;
阵列适配器;
列表视图列表视图;
静态蓝牙适配器;
设置设备阵列;
阵列列表对设备;
阵列列表设备;
过滤器;
广播接收机;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u蓝牙);
init();
if(btAdapter==null){
Toast.makeText(getApplicationContext(),“未检测到蓝牙”,0.show();
完成();
}否则{
如果(!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
私有无效开始发现(){
//TODO自动生成的方法存根
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
私有无效转换{
意向意向=新意向(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(意向,1);
}
私有void getPairedDevices(){
DeviceArray=btAdapter.getBondedDevices();
如果(DeviceArray.size()>0){
用于(蓝牙设备:设备阵列){
pairedDevices.add(device.getName());
}
}
}
私有void init(){
listView=(listView)findViewById(R.id.listView);
setOnItemClickListener(this);
listAdapter=newArrayAdapter(这是android.R.layout.simple\u list\u item\u 1,0);
setAdapter(listAdapter);
btAdapter=BluetoothAdapter.getDefaultAdapter();
pairedDevices=新的ArrayList();
筛选器=新的IntentFilter(BluetoothDevice.ACTION\u已找到);
设备=新的ArrayList();
接收器=新的广播接收器(){
@凌驾
公共void onReceive(上下文、意图){
String action=intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(ACTION)){
BluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA\u设备);
设备。添加(设备);
字符串s=“”;

对于(int a=0;a什么是Bluetooth.MESSAGE_READ?这是Bluetooth类。我在下面添加了它。所以您有:buffer=new byte[1024];您想将缓冲区大小更改为512?我不明白。。。