1. 程式人生 > >Android開發之藍芽Socket

Android開發之藍芽Socket

藍芽Socket程式設計

實現藍芽Socket伺服器

藍芽Server端就是通過執行緒來註冊一個具有名稱和唯一識別的UUID號的BluetoothServerSocket, 然後就一直監聽Client端(BluetoothSocket)的請求,並對這些請求做出相應的處理。

// 註冊藍芽Server

BleutoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

BluetoothServerSocket serverSocket = bluetooth.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM

, UUID.fromString(“xxxx-xxxx-xxxx-xxxx-xxxx”));

引數PROTOCOL_SCHEME_RFCOMM是一個String型別的常量,表示藍芽Server的名稱,而UUID.fromString()表示藍芽Server的唯一標識UUID。

在Client連線到Server時需要使用該UUID號。

// 接收Client的連線請求

BluetoothSocket socket = serverSocket.accept();

// 處理請求內容

if(socket != null) { }

// 關閉藍芽Server

serverSocket.close();

示例完整程式碼

public class ServerSocketActivity extends ListActivity {

    // 一些常量,表示Server的名稱

    public static final String PROTOCOL_SCHEME_L2CAP = “btl2cap”;

    public static final String PROTOCOL_SCHEME_RFCOMM = “btspp”;

    public static final String PROTOCOL_SCHEME_BT_OBEX = “btobex”;

    public static final String PROTOCOL_SCHEME_TCP_OBEX

= “tcpobex”;

    private Handler mHandler = new Handler();

    private BleutoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

    private BluetoothServerSocket serverSocket;

    private Thread serverWorker = new Thread(){

        public void run(){

            listen();

        }

    };

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayouParams.FLAG_BLUE_BEHIND, WindowManager.LayouParams.FLAG_BLUE_BEHIND);

        setContentView(R.layout.server_socket);

        if(!bluetooth.isEnabled()){

            finish();       

            return;

        }

        serverWorker.start();

    }

    protected void onDestroy() {

        super.onDestroy();

        shutdownServer();

    }

    protected void finalize() throws Throwable {

        super.finalize();

        shutdownServer();

    }

    private void shutdownServer() {

        // Why does it create a thread below ?

        new Thread() {

            public void run() {

                serverWorker.interrupt();

                if(serverSocket!=null) {

                    try {

                        serverSocket.close();

                    } catch(IOException ex) { }

                }           

            }

        }.start();

    }

    public void onButtonClicked(View view) {

        shutdownServer();

    }

    protected void listen() {

        try {           

            serverSocket = bluetooth.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM, UUID.fromString(“xxxx-xxxx-xxxx-xxxx-xxxx”));

            // Client連線列表

            final List<String> lines = new ArrayList<String>();

            mHandler.post(new Runnable(){

                public void run(){

                    lines.add(“server started …”);

                    ArrayAdaper<String> adpater = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, lines);

                    setListAdapter(adapter);

                }

            });

            BluetoothSocket socket = serverSocket.accept();

            // 處理請求內容

            if(socket!=null){

                InputStream is = socket.getInputStream();

                int read = –1;

                final byte[] bytes = new byte[2048];

                while((read = is.read(bytes)) > -1) {

                    final int count = read;

                    mHandler.post(new Runnable() {

                        public void run() {    
                            StringBuilder builder = new StringBuilder();

                            // …

                            lines.add(builder.toString());

                            ArrayAdaper<String> adpater = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, lines);

                            setListAdapter(adapter);

                        }

                    });

                } // while

            } // if

        }  catch (IOException ex) { }

    } // listen()

}

public class ClientSocketActivity extends Activity {

    private static final int REQUEST_DISCOVERY = 0x1;

    private Handler mHandler = new Handler();

    private BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayouParams.FLAG_BLUE_BEHIND, WindowManager.LayouParams.FLAG_BLUE_BEHIND);

        setContentView(R.layout.client_socket);

        if(!bluetooth.isEnabled()){

            finish();       

            return;

        }

        Intent it = new Intent(mContext, DiscoveryActivity.class);

        Toast.makeText(mContext, “select device to connect.”, Toast.LENGTH_SHORT).show();

        startActivityForResult(it, REQUEST_DISCOVERY);

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode != REQUEST_DISCOVERY || resultCode != RESULT_OK) {

            return;

        }

        final BluetoothDevice device = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        new Thread(){

            public void run() {

                connect(device);

            }

        }.start();

    }

    protected void connect(BluetoothDevice device) {

        BluetoothSocket socket = null;

        try {

            // socket = device.createRfcommSocketToServiceRecord(BluetoothProtocols.OBEX_OBJECT_PUSH_PROTOCOL_UUID);

            socket = device.createRfcommSocketToServiceRecord(UUID.fromString(“xxxx-xxxx-xxxx-xxxx”));

            socket.connect();

        } catch (IOException ex) {

        } finally {

            socket.close();

        }

    }

}