通过android连接蓝牙

时间:2014-04-08 08:49:51

标签: android bluetooth connection

我想将我的设备(HTC Wildfire S)与OBD2 Dongle连接。 为此我已经写了一个基于Google Developer的蓝牙程序。 如果我尝试在设备上运行apk,我会得到一个异常,返回false。 所以连接没有运行。 有谁能够帮我?! 我是这个论坛的新人。对不起我的英语不好。这不是我的最爱languange =)

在Manifest中我设置了蓝牙和蓝牙管理员权限。

这里是Main,Activity和Manifest的源代码。

主:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity{

    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private ConnectedThread connected;
    private boolean isConnected = false;



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


    //Button ruft die Methode verbindung auf!!!!
    public void verbinden(View view){
        verbindung();
     }


  //Verbindung wird ausgeführt
    private void verbindung(){          //Muss mit Button aufgerufen werden
        String address = "B8:E8:56:41:74:09";       //Adresse vom Dongle
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        ConnectThread connect = new ConnectThread(device);
        connect.start();
        //connected.write(null);
    }



    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
                Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                tmp = (BluetoothSocket) m.invoke(device, 1);
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mmSocket = tmp;
        }

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

            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                boolean b = mmSocket.isConnected(); System.out.println(b);
                mmSocket.connect();
                isConnected = true;
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                System.out.println("Ich bin eine Exception.");
                try {
                    mmSocket.close();
                } catch (IOException closeException) { }
                return;
            }

            connected = new ConnectedThread(mmSocket);
            connected.run();
        }

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

        private 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;
        }

        public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // 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(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
                connected.write(null);
            } catch (IOException e) {}
        }

        /* Call this from the main activity to shutdown the connection */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
}

的活动:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.blue_final.MainActivity$PlaceholderFragment" >

    <Button
        android:id="@+id/BtnVerbinden"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:onClick="verbinden"
        android:text="verbinden" />

    <Button
        android:id="@+id/BtnSenden"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/BtnVerbinden"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/BtnVerbinden"
        android:layout_marginBottom="17dp"
        android:onClick="senden"
        android:text="Senden" />

    <EditText
        android:id="@+id/TFKonsole"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/BtnSenden"
        android:layout_alignLeft="@+id/BtnVerbinden"
        android:layout_alignRight="@+id/BtnVerbinden"
        android:layout_below="@+id/BtnVerbinden"
        android:ems="10" />

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

你得到什么样的例外? 应用程序启动时或按BtnVerbinden时会出现异常吗? 此外,请确保Dongle与您的Android设备配对。 请提供一些更详细的信息例外。

编辑:

我尝试了你的代码。 基本上它正在工作,我按下按钮并成功连接到另一台设备。

答案 1 :(得分:0)

我的OBD II适配器出了些问题。他坏了。现在我有一个新的。 它工作正常。