在Android上从蓝牙接收数据

时间:2016-04-16 20:49:54

标签: java android bluetooth

我已经编写了一些用于从蓝牙模块(HC-05)接收数据的代码,我想阅读字符串'#900~'来自Arduino,但我没有得到任何答复。我已经与模块建立了联系,但仅此而已。我只需要在Android上阅读。这可能很容易,但我无法理解:/。我究竟做错了什么?它下面是我的代码:

package nichten.pneumobil;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class MainApplication extends AppCompatActivity {
    boolean doubleBackToExitPressedOnce = false;

    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    static BluetoothSocket mmSocket;
    static BluetoothDevice mmDevice;                 
    static OutputStream mmOutputStream;
    static InputStream mmInputStream;
    private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    private String BTdevice = "POJAZD1";
    private boolean polaczenie = false;

    Handler bluetoothIn;
    final int handlerState = 0;
    private ConnectedThread mConnectedThread;
    private StringBuilder recDataString = new StringBuilder();

    private Button btnModuleConnect;

    private TextView txtModuleConnect;
    private TextView txtTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_application);

        btnModuleConnect = (Button) findViewById(R.id.btnModuleConnect);

        txtModuleConnect = (TextView) findViewById(R.id.txtModuleConnect);
        txtTest = (TextView) findViewById(R.id.txtTest);

        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }

        btnModuleConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (connectWithModule())
                        txtModuleConnect.setText("Connection status: Connected");
                    else
                        txtModuleConnect.setText("Connection status: Module not found");
                } catch(IOException e){
                    e.printStackTrace();
                }
            }
        });

        bluetoothIn = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (msg.what == handlerState) {
                    String readMessage = (String) msg.obj;
                    recDataString.append(readMessage);
                    int endOfLineIndex = recDataString.indexOf("~");
                    if (endOfLineIndex > 0) {
                        String dataInPrint = recDataString.substring(0, endOfLineIndex);

                        int dataLength = dataInPrint.length();


                        if (recDataString.charAt(0) == '#')
                        {
                            txtTest.setText(recDataString);
                        }
                        recDataString.delete(0, recDataString.length());

                        dataInPrint = " ";
                    }
                }
            }
        };
    }

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            disconnectWithModule();
            mBluetoothAdapter.disable();
            finish();
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce=false;
            }
        }, 2000);
    }

    public boolean connectWithModule() throws IOException {
        if(polaczenie){
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmDevice = null;
            mmSocket = null;
            mBluetoothAdapter = null;
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if(device.getName().equals(BTdevice)){
                    mmDevice = device;
                    break;
                }
            }
        }

        if (mmDevice != null) {
            try {
                mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
                mmSocket.connect();

                Toast.makeText(getApplicationContext(), "Połączono!", Toast.LENGTH_SHORT).show();

                polaczenie = true;
                mmOutputStream = mmSocket.getOutputStream();
                mmInputStream = mmSocket.getInputStream();
                return true;

            } catch (Exception e2) {
                Toast.makeText(getApplicationContext(),"Nie udało się połaczyć.", Toast.LENGTH_SHORT).show();
                mmDevice = null;

                try {
                    mmSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                mmSocket = null;
            }
        }
        else if (mmDevice == null){
            Toast.makeText(getApplicationContext(), "Nie ma sparowanych urządzeń.", Toast.LENGTH_SHORT).show();
            polaczenie = false;
        }

        return false;
    }

    public void disconnectWithModule(){
        if (polaczenie) {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

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

            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[256];
            int bytes;

            while (true) {
                try {
                    bytes = mmInStream.read(buffer);
                    String readMessage = new String(buffer, 0, bytes);
                    bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
                } catch (IOException e) {
                    break;
                }
            }
        }
        //write method
        public void write(String input) {
            byte[] msgBuffer = input.getBytes();
            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
                finish();

            }
        }
    }
}

我是Android的初学者(仅用2天时间:P),但我不知道该怎么做。我还包括我的AndroidManifest,我的其他活动,也许它有助于找出问题所在:

package nichten.pneumobil;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);

        btnNextScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent nextScreen = new Intent(getApplicationContext(), MainApplication.class);
                startActivity(nextScreen);
            }
        });
    }
}

并表明:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="nichten.pneumobil">

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainApplication"
                android:screenOrientation="landscape">
        </activity>
    </application>

</manifest>

0 个答案:

没有答案