1. 程式人生 > >Android的藍芽 開啟 關閉 配對 監聽 連結

Android的藍芽 開啟 關閉 配對 監聽 連結

這篇文章以程式碼為主,適合初學者。

這是一個兩個android手機之間相連線的程式碼,中間有開啟、關閉、discoverable設定、配對、連結監聽、連結和連結後資料處理的例項。

初始化:

1.AndroidManifest.xml中的許可權配置

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android
:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" /> <permission android:name="android.permission.BLUETOOTH_ADMIN" /> <permission
android:name="android.permission.ACCESS_FINE_LOCATION" /> <permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

UUID:

private static final UUID BTMODULEUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

開啟:

private void onClinkBluetoothOn(View view){
    if(!mBTAdapter
.isEnabled()){ mBTAdapter.enable(); Toast.makeText(this,"Opening Bluetooth", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this,"Bluetooth is already on!",Toast.LENGTH_SHORT).show(); } }

關閉:

private void onClinkBluetoothOff(View view){
    if(mBTAdapter.isEnabled()){
        mBTAdapter.disable();
        Toast.makeText(this,"Turned off Bluetooth", Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(this,"Bluetooth is already off!",Toast.LENGTH_SHORT).show();
    }
}

可被發現,discoverable:

private void onClinkBluetoothDiscoverable(View view){
    try {
        Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
        setDiscoverableTimeout.setAccessible(true);
        Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
        setScanMode.setAccessible(true);

        setDiscoverableTimeout.invoke(mBTAdapter, 1);
        setScanMode.invoke(mBTAdapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,1);
        ///mBTAdapter.get
}catch (Exception e){
        Toast.makeText(getBaseContext(), "Socket Creation failed!",Toast.LENGTH_SHORT).show();
    }
}

配對:

try {
    if(mBTAdapter.isDiscovering()) mBTAdapter.cancelDiscovery();

    if(mBTDevice.getBondState() == BluetoothDevice.BOND_NONE){
        Method createBond = BluetoothDevice.class.getMethod("createBond");
        createBond.invoke(mBTDevice);
    }
}catch (Exception e){
    e.printStackTrace();

}

監聽:

private class socketListenThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    public socketListenThread(){
        BluetoothServerSocket tmp = null;
        try {
            tmp = mBTAdapter.listenUsingRfcommWithServiceRecord(NAME_SERVER, BTMODULEUUID);

        }catch (Exception e){
            e.printStackTrace();
        }
        mmServerSocket = tmp;
    }

    public void run(){
        BluetoothSocket socket = null;

        while(mState != STATE_CONNECTED){
            try {
                socket = mmServerSocket.accept();

                if(socket.isConnected()){

                    mConnectedThread = new connectedThread(socket);
                    mConnectedThread.start();

                    break;
                }

            }catch (Exception e){
                try {
                    mmServerSocket.close();
                }catch (Exception e1){
                    e1.printStackTrace();
                }

                e.printStackTrace();
            }
        }
    }

    public void cancel(){
        try {
            mState = STATE_CONNECTED;
            if(mmServerSocket != null) mmServerSocket.close();

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

連結:

private AdapterView.OnItemClickListener mClickDeviceListListener = new AdapterView.OnItemClickListener(){
    @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(!mBTAdapter.isEnabled()){
            Toast.makeText(getBaseContext(),"Bluetooth not on", Toast.LENGTH_SHORT).show();
        }

        String info = ((TextView) view).getText().toString();
        final String address = info.substring(info.length()-17);
        final String name = info.substring(0,info.length()-17);

        mBTDevice = mBTAdapter.getRemoteDevice(address);

        try {
            if(mBTAdapter.isDiscovering()) mBTAdapter.cancelDiscovery();

            if(mBTDevice.getBondState() == BluetoothDevice.BOND_NONE){
                Method createBond = BluetoothDevice.class.getMethod("createBond");
                createBond.invoke(mBTDevice);
            }
        }catch (Exception e){
            e.printStackTrace();

        }

        //create a new thread to avoid blocking the GUI
new  Thread()
        {
            public void run(){
                ///BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
try {
                    if(mBTAdapter.isDiscovering()) mBTAdapter.cancelDiscovery();
                    mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(BTMODULEUUID);

                    //mBTSocket = createB
}catch (Exception e){
                    Toast.makeText(getBaseContext(), "Socket Creation failed!",Toast.LENGTH_SHORT).show();
                }

                try{
                    mBTSocket.connect();

                    mConnectedThread = new connectedThread(mBTSocket);
                    mConnectedThread.start();


                }catch (Exception e){
                    try {
                        mBTSocket.close();
                    }catch (Exception e2){
                        Toast.makeText(getBaseContext(),"Socket Creation failed", Toast.LENGTH_SHORT).show();
                    }
                }

            }

        }.start();


    }
};

資料傳輸:

private class connectedThread extends Thread{

    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public connectedThread(BluetoothSocket socket){
        InputStream mmIn = null;
        OutputStream mmOut = null;

        mmSocket = socket;

        try {
            mmIn = socket.getInputStream();
            mmOut = socket.getOutputStream();
        }catch (Exception e){
            e.printStackTrace();
        }
        mState = STATE_CONNECTED;
        mmInStream = mmIn;
        mmOutStream = mmOut;

    }

    public void run(){
        byte[] readBuffer = new  byte[1024];
        int bytes;

        while(mmSocket.isConnected()){
            try {
                Thread.sleep(20);
                bytes = mmInStream.read(readBuffer);

                mHandlerMessage.obtainMessage(InterfaceCommon.MESSAGE_READ_SOCKET, bytes, -1, readBuffer).sendToTarget();

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }///run()
public void write(byte[] buffer){
        try {
            mmOutStream.write(buffer);
            mHandlerMessage.obtainMessage(InterfaceCommon.MESSAGE_WRITE_SOCKET, buffer.length, -1, buffer).sendToTarget();


        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void cancel(){
        try {
            mmSocket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }


}///connectedThread