androd stdio 编写蓝牙通信程序

来源:互联网 发布:乌镇互联网大会 知乎 编辑:程序博客网 时间:2024/06/03 18:15

一个简答的蓝牙安卓Service,自动连接手机已经配对的蓝牙模块实现串口通信。

package com.example.sky.bluetooth;import android.Manifest;import android.app.Service;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.bluetooth.BluetoothSocket;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Binder;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.support.v4.app.ActivityCompat;import android.widget.Toast;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Iterator;import java.util.Set;import java.util.Timer;import java.util.TimerTask;import java.util.UUID;import static android.widget.Toast.LENGTH_SHORT;public class BlueToothService extends Service {    static final String SerialPortServiceClass_UUID = "00001101-0000-1000-8000-00805F9B34FB";    public static final int CONNECT_FAIL = 0;    public static final int CONNECT_SUCESS = 1;    static final int SEND_ERROR = 0;    static final int SEND_SUCCESS = 1;    final char ALARM_CHAR = 0x65;    final char NORMAL_CHAR = 0x60;    char dateget = 0x00;    private String deviceid;    BluetoothSocket socket = null;    Set<BluetoothDevice> devices;    BluetoothDevice device;    InputStream inputStream = null;    OutputStream outputStream = null;    private int state = CONNECT_FAIL;    BlueToothBinder binder = new BlueToothBinder();    Timer timer = new Timer();    Handler handler = new Handler() {        public void handleMessage(Message msg) {            switch (msg.what) {                //针对监听到的消息进行处理            }        }    };
    TimerTask task = new TimerTask() {        @Override        public void run() {            dateget = getInput();            handler.sendEmptyMessage(dateget);        }    };    public BlueToothService() {    }    @Override    public IBinder onBind(Intent intent) {        if(linkBlueTooth()){            connect(device);        }        return binder;    }    @Override    public boolean onUnbind(Intent intent) {        if(state==CONNECT_FAIL)            return true;        else{            state = CONNECT_FAIL;            try {                socket.close();            } catch (IOException e) {                return false;            }        }        return super.onUnbind(intent);    }    private boolean linkBlueTooth() {        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();        //adapter不等于null,说明本机有蓝牙设备        if (adapter != null) {            Toast.makeText(this, "No Bluetooth device", LENGTH_SHORT).show();            //如果蓝牙设备未开启            if (!adapter.isEnabled()) {                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                //请求开启蓝牙设备                try {                    startActivity(intent);                }catch (Exception e){                    Toast.makeText(this, "open blue tooth failed", LENGTH_SHORT).show();                }            }            //获得已配对的远程蓝牙设备的集合            devices = adapter.getBondedDevices();            if (devices.size() > 0) {                for (Iterator<BluetoothDevice> it = devices.iterator(); it.hasNext(); ) {                    device = (BluetoothDevice) it.next();                    //打印出远程蓝牙设备的物理地址                    Toast.makeText(this, device.getAddress() + "link", LENGTH_SHORT).show();                    //deviceid = device.getAddress();                }                return true;            } else {                Toast.makeText(this, "还没有已配对的远程蓝牙设备!", LENGTH_SHORT).show();                return false;            }        } else {            Toast.makeText(this, "本机没有蓝牙设备!", LENGTH_SHORT).show();            return false;        }    }    protected void connect(BluetoothDevice device) {        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();        try {            socket = device.createRfcommSocketToServiceRecord(UUID.fromString(SerialPortServiceClass_UUID));            socket.connect();            inputStream = socket.getInputStream();            outputStream = socket.getOutputStream();            outputStream.write(0x66);            state = CONNECT_SUCESS;            Toast.makeText(this, "connect success!", LENGTH_SHORT).show();        } catch (Exception ex) {            Toast.makeText(this, "connect error!", LENGTH_SHORT).show();        }    }    private char getInput(){        char c = 0x00;        if(inputStream==null){            return 0x00;        }        try {            c = (char) inputStream.read();        } catch (IOException e) {            return 0x00;        }        return c;    }    class BlueToothBinder extends Binder {        public int outputChar(char c){            if(outputStream==null){                return SEND_ERROR;            }            else{                try {                    outputStream.write(c);                } catch (IOException e) {                    return SEND_ERROR;                }            }            return SEND_SUCCESS;        }        public void setAlarmPhone(String phone){            alarmphone = phone;            //Toast.makeText(getApplicationContext(),alarmphone,LENGTH_SHORT).show();        }        public void startAlarm(){            timer.schedule(task,0,100);        }        public void endAlarm(){            try {                task.cancel();                timer.cancel();            }catch (Exception e){            }        }        public char inputChar(){            char c = 0x00;            if(inputStream==null){                return 0x00;            }            try {                c = (char) inputStream.read();            } catch (IOException e) {                return 0x00;            }            return c;        }        public String getDeviceId(){            if(device!=null)                return device.getAddress();            return "ff-ff-ff-ff-ff-ff";        }        public int getState(){            return state;        }    }
使用时通过绑定服务返回的BlueToothBinder类的实例进行发送数据或接收数据


原创粉丝点击