First three characters missing from string when send from android via bluetooth

可紊 提交于 2020-01-26 04:15:48

问题


When I send "M" String to the Device I call time function from where I make my String.

Code:

` mManButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            man = 1;

            clearScreen();

            mManButton.setBackgroundResource(R.color.button_pressed);
            mStartButton.setBackgroundResource(R.color.button_default);
            mCalButton.setBackgroundResource(R.color.button_default);
            mTestButton.setBackgroundResource(R.color.button_default);
            mLinearButtton.setBackgroundResource(R.color.button_default);
            mAutoButton.setBackgroundResource(R.color.button_default);
            // Send a message using content of the edit text widget

            sendMessage("M");
            time();
        }

    });`

Then the time() function is called. Here if my day is Monday then the variable day is set to 1. That means in this function I am creating a String which has Date Format values in it. This string starts from "A" and ends with "B".

Code :

 private void time()
{
    int day = 0;
    Date now = new Date();
    String sdf = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(now);

    switch(sdf){
        case ("Monday"):
            day = 1;
            break;
        case("Tuesday"):
            day = 2;
            break;
        case ("Wednesday"):
            day = 3;
            break;
        case ("Thursday"):
            day = 4;
            break;
        case("Friday"):
            day = 5;
            break;
        case ("Saturday"):
            day = 6;
            break;
        case("Sunday"):
            day = 7;
            break;
    }

    int mm = Calendar.getInstance().get(Calendar.MINUTE);
    int HH = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    int dd = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    int MM = Calendar.getInstance().get(Calendar.MONTH)+1;
    int yy = Calendar.getInstance().get(Calendar.YEAR)%100;

    if(mm<10) {
        String time1 = "A" + "0" + mm + HH + "0" + day + dd + MM + yy + "B"; //suppose time1 = A041303211216B
        tv7.setText("Please Wait..");
        int p = 0;
        while (p < time1.length())
        {
            char zx = time1.charAt(p);
            String xz = String.valueOf(zx);
            sendMessage(xz);
            p++;
        }
    }
    else if(mm>=10) {
        String time2 = "A" + mm + HH + "0" + day + dd + MM + yy + "B"; **//suppose time2 = A151303211216B**
        tv7.setText("Please Wait..");
        int k = 0;
        while (k < time2.length())
        {
            char zx = time2.charAt(k);
            String xz = String.valueOf(zx);
            sendMessage(xz);
            k++;
        }
    }
}

When the string is created I send each characters of the string to sendMessage().

Code :

private void sendMessage(String message) {
    // Check that we're actually connected before trying anything
    if (mChatService.getState() !=
            com.example.hasani.bluetoothterminal.BluetoothChatService.STATE_CONNECTED) {
        Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
        mStartButton.setBackgroundResource(R.color.button_default);
        mCalButton.setBackgroundResource(R.color.button_default);
        mTestButton.setBackgroundResource(R.color.button_default);
        mManButton.setBackgroundResource(R.color.button_default);
        mAutoButton.setBackgroundResource(R.color.button_default);
        return;
    }

    // Check that there's actually something to send
    if (message.length() > 0) {
        // Get the message bytes and tell the BluetoothChatService to write
        byte[] send = message.getBytes();
        mChatService.write(send);

        // Reset out string buffer to zero and clear the edit text field
        mOutStringBuffer.setLength(0);
    }
}

The write function.

Code :

public void write(byte[] out) {
    // Create temporary object
    ConnectedThread r;
    // Synchronize a copy of the ConnectedThread
    synchronized (this) {
        if (mState != STATE_CONNECTED) return;
        r = mConnectedThread;
    }
    // Perform the write unsynchronized
    r.write(out);
}

The wite in ConnectedThread Code :

public void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);

            // Share the sent message back to the UI Activity
            mHandler.obtainMessage(com.example.hasani.bluetoothterminal.Constants.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

As there is a role of Handler in it. The issue is when debugging step by step, each character is sent to the other Device and that device receives each and every string from "A" to "B", thus there is no problem.

But when i run My android app, after sending "M", the time() function is called and the String is sent but the first three characters of the string i.e; "Amm" is not received by the device. I still don't understand what is causing the problem. Please Help!. Will be appreciated. Thank You!


回答1:


Ohkay wait!!! I got the solution. In case if someone go through the same kind of situation. In my onClickListener I call my time() function after a 5 second delay using a second handler.

My onClickListener code is :

mManButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            man = 1;
            linear = 0;
            auto = 0;
            cal = 0;
            test = 0;
            linear = 0;
            clearScreen();

            mManButton.setBackgroundResource(R.color.button_pressed);
            mStartButton.setBackgroundResource(R.color.button_default);
            mCalButton.setBackgroundResource(R.color.button_default);
            mTestButton.setBackgroundResource(R.color.button_default);
            mLinearButtton.setBackgroundResource(R.color.button_default);
            mAutoButton.setBackgroundResource(R.color.button_default);
            // Send a message using content of the edit text widget

            sendMessage("M");
            tv7.setText("Please wait....");
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    time();
                }
            },5000);
        }

    });

My time() function is :

private void time() {
    int day = 0;
    Date now = new Date();
    String sdf = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(now);

    switch (sdf) {

        case ("Monday"):
            day = 1;
            break;
        case ("Tuesday"):
            day = 2;
            break;
        case ("Wednesday"):
            day = 3;
            break;
        case ("Thursday"):
            day = 4;
            break;
        case ("Friday"):
            day = 5;
            break;
        case ("Saturday"):
            day = 6;
            break;
        case ("Sunday"):
            day = 7;
            break;
    }

    int mm = Calendar.getInstance().get(Calendar.MINUTE);
    int HH = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    int dd = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    int MM = Calendar.getInstance().get(Calendar.MONTH)+1;
    int yy = Calendar.getInstance().get(Calendar.YEAR)%100;


    String A = "A";
    String min = String.format("%02d",mm);
    String hour = String.format("%02d",HH);
    String d = String.format("%02d",day);
    String date = String.format("%02d",dd);
    String month = String.format("%02d",MM);
    String year = String.format("%02d",yy);
    String B = "B";

    String time2 = A+min+hour+d+date+month+year+B;
    sendMessage(time2);
}

Now i can receive correct data as I required. My application works like a charm.




回答2:


To expand on my comment, the simplest way to handle waiting to connect would be thus. First, return success or failure from write():

public boolean write(byte[] out) {
    // Create temporary object
    ConnectedThread r;
    // Synchronize a copy of the ConnectedThread
    synchronized (this) {
        if (mState != STATE_CONNECTED) return false;
        r = mConnectedThread;
    }
    // Perform the write unsynchronized
    r.write(out);
    return true;
}

Then in sendMessage(), replace mChatService.write(send); with:

while (!mChatService.write(send))
{
    try {
        Thread.sleep(10);
    }
    catch(InterruptedException ex) {
        // Uncomment to just give up
        //break;
    }
}

This will wait another 10 milliseconds or so before trying to resend.

There's of course a lot of improvements to make like only allowing a few retries before giving up completely, etc.

On a related note, with the above change you can probably do:

sendMessage(time1);

instead of doing it a character at a time.

Finally, your time formatting can be simplified to:

Calendar cal = Calendar.getInstance();
Date date = cal.getTime();             
SimpleDateFormat format = new SimpleDateFormat("mmHHcddMMYY");
String time = "A" + format1.format(date) + "B";            

Or something like that. See this page for details.



来源:https://stackoverflow.com/questions/41255530/first-three-characters-missing-from-string-when-send-from-android-via-bluetooth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!