Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Android上接收蓝牙数据_Java_Android_Bluetooth - Fatal编程技术网

Java 在Android上接收蓝牙数据

Java 在Android上接收蓝牙数据,java,android,bluetooth,Java,Android,Bluetooth,我已经编写了一些从蓝牙模块(HC-05)接收数据的代码,我想从Arduino读取字符串“#900~”,但没有得到任何响应。我已与模块建立了连接,但仅此而已。我只需要在Android上阅读。这可能是一项简单的任务,但我无法理解:/。我做错了什么?下面是我的代码: package nichten.pneumobil; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import

我已经编写了一些从蓝牙模块(HC-05)接收数据的代码,我想从Arduino读取字符串“#900~”,但没有得到任何响应。我已与模块建立了连接,但仅此而已。我只需要在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();

            }
        }
    }
}
并表明:

<?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>

<?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>