Android藍(lán)牙通信編程
項(xiàng)目涉及藍(lán)牙通信,所以就簡(jiǎn)單的學(xué)了學(xué),下面是自己參考了一些資料后的總結(jié),希望對(duì)大家有幫助。
以下是開發(fā)中的幾個(gè)關(guān)鍵步驟:
1、首先開啟藍(lán)牙
2、搜索可用設(shè)備
3、創(chuàng)建藍(lán)牙socket,獲取輸入輸出流
4、讀取和寫入數(shù)據(jù)
5、斷開連接關(guān)閉藍(lán)牙
下面是一個(gè)藍(lán)牙聊天demo
效果圖:

在使用藍(lán)牙是 BluetoothAdapter 對(duì)藍(lán)牙開啟,關(guān)閉,獲取設(shè)備列表,發(fā)現(xiàn)設(shè)備,搜索等核心功能
下面對(duì)它進(jìn)行封裝:
package com.xiaoyu.bluetooth;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
public class BTManage {
// private List<BTItem> mListDeviceBT=null;
private BluetoothAdapter mBtAdapter =null;
private static BTManage mag=null;
private BTManage(){
// mListDeviceBT=new ArrayList<BTItem>();
mBtAdapter=BluetoothAdapter.getDefaultAdapter();
}
public static BTManage getInstance(){
if(null==mag)
mag=new BTManage();
return mag;
}
private StatusBlueTooth blueStatusLis=null;
public void setBlueListner(StatusBlueTooth blueLis){
this.blueStatusLis=blueLis;
}
public BluetoothAdapter getBtAdapter(){
return this.mBtAdapter;
}
public void openBluetooth(Activity activity){
if(null==mBtAdapter){ ////Device does not support Bluetooth
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle("No bluetooth devices");
dialog.setMessage("Your equipment does not support bluetooth, please change device");
dialog.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
return;
}
// If BT is not on, request that it be enabled.
if (!mBtAdapter.isEnabled()) {
/*Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(enableIntent, 3);*/
mBtAdapter.enable();
}
}
public void closeBluetooth(){
if(mBtAdapter.isEnabled())
mBtAdapter.disable();
}
public boolean isDiscovering(){
return mBtAdapter.isDiscovering();
}
public void scanDevice(){
// mListDeviceBT.clear();
if(!mBtAdapter.isDiscovering())
mBtAdapter.startDiscovery();
}
public void cancelScanDevice(){
if(mBtAdapter.isDiscovering())
mBtAdapter.cancelDiscovery();
}
public void registerBluetoothReceiver(Context mcontext){
// Register for broadcasts when start bluetooth search
IntentFilter startSearchFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
mcontext.registerReceiver(mBlueToothReceiver, startSearchFilter);
// Register for broadcasts when a device is discovered
IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
mcontext.registerReceiver(mBlueToothReceiver, discoveryFilter);
// Register for broadcasts when discovery has finished
IntentFilter foundFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
mcontext.registerReceiver(mBlueToothReceiver, foundFilter);
}
public void unregisterBluetooth(Context mcontext){
cancelScanDevice();
mcontext.unregisterReceiver(mBlueToothReceiver);
}
public List<BTItem> getPairBluetoothItem(){
List<BTItem> mBTitemList=null;
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
Iterator<BluetoothDevice> it=pairedDevices.iterator();
while(it.hasNext()){
if(mBTitemList==null)
mBTitemList=new ArrayList<BTItem>();
BluetoothDevice device=it.next();
BTItem item=new BTItem();
item.setBuletoothName(device.getName());
item.setBluetoothAddress(device.getAddress());
item.setBluetoothType(BluetoothDevice.BOND_BONDED);
mBTitemList.add(item);
}
return mBTitemList;
}
private final BroadcastReceiver mBlueToothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
if(blueStatusLis!=null)
blueStatusLis.BTDeviceSearchStatus(StatusBlueTooth.SEARCH_START);
}
else if (BluetoothDevice.ACTION_FOUND.equals(action)){
// When discovery finds a device
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
BTItem item=new BTItem();
item.setBuletoothName(device.getName());
item.setBluetoothAddress(device.getAddress());
item.setBluetoothType(device.getBondState());
if(blueStatusLis!=null)
blueStatusLis.BTSearchFindItem(item);
// mListDeviceBT.add(item);
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
// When discovery is finished, change the Activity title
if(blueStatusLis!=null)
blueStatusLis.BTDeviceSearchStatus(StatusBlueTooth.SEARCH_END);
}
}
};
}
藍(lán)牙開發(fā)和socket一致,分為server,client
server功能類封裝:
package com.xiaoyu.bluetooth;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.UUID;
import com.xiaoyu.utils.ThreadPool;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
public class BTServer {
/* 一些常量,代表服務(wù)器的名稱 */
public static final String PROTOCOL_SCHEME_L2CAP = "btl2cap";
public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";
public static final String PROTOCOL_SCHEME_BT_OBEX = "btgoep";
public static final String PROTOCOL_SCHEME_TCP_OBEX = "tcpobex";
private BluetoothServerSocket btServerSocket = null;
private BluetoothSocket btsocket = null;
private BluetoothAdapter mBtAdapter =null;
private BufferedInputStream bis=null;
private BufferedOutputStream bos=null;
private Handler detectedHandler=null;
public BTServer(BluetoothAdapter mBtAdapter,Handler detectedHandler){
this.mBtAdapter=mBtAdapter;
this.detectedHandler=detectedHandler;
}
public void startBTServer() {
ThreadPool.getInstance().excuteTask(new Runnable() {
public void run() {
try {
btServerSocket = mBtAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
Message msg = new Message();
msg.obj = "請(qǐng)稍候,正在等待客戶端的連接...";
msg.what = 0;
detectedHandler.sendMessage(msg);
btsocket=btServerSocket.accept();
Message msg2 = new Message();
String info = "客戶端已經(jīng)連接上!可以發(fā)送信息。";
msg2.obj = info;
msg.what = 0;
detectedHandler.sendMessage(msg2);
receiverMessageTask();
} catch(EOFException e){
Message msg = new Message();
msg.obj = "client has close!";
msg.what = 1;
detectedHandler.sendMessage(msg);
}catch (IOException e) {
e.printStackTrace();
Message msg = new Message();
msg.obj = "receiver message error! please make client try again connect!";
msg.what = 1;
detectedHandler.sendMessage(msg);
}
}
});
}
private void receiverMessageTask(){
ThreadPool.getInstance().excuteTask(new Runnable() {
public void run() {
byte[] buffer = new byte[2048];
int totalRead;
/*InputStream input = null;
OutputStream output=null;*/
try {
bis=new BufferedInputStream(btsocket.getInputStream());
bos=new BufferedOutputStream(btsocket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
// ByteArrayOutputStream arrayOutput=null;
while((totalRead = bis.read(buffer)) > 0 ){
// arrayOutput=new ByteArrayOutputStream();
String txt = new String(buffer, 0, totalRead, "UTF-8");
Message msg = new Message();
msg.obj = txt;
msg.what = 1;
detectedHandler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public boolean sendmsg(String msg){
boolean result=false;
if(null==btsocket||bos==null)
return false;
try {
bos.write(msg.getBytes());
bos.flush();
result=true;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public void closeBTServer(){
try{
if(bis!=null)
bis.close();
if(bos!=null)
bos.close();
if(btServerSocket!=null)
btServerSocket.close();
if(btsocket!=null)
btsocket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
client功能封裝:
package com.xiaoyu.bluetooth;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.xiaoyu.utils.ThreadPool;
public class BTClient {
final String Tag=getClass().getSimpleName();
private BluetoothSocket btsocket = null;
private BluetoothDevice btdevice = null;
private BufferedInputStream bis=null;
private BufferedOutputStream bos=null;
private BluetoothAdapter mBtAdapter =null;
private Handler detectedHandler=null;
public BTClient(BluetoothAdapter mBtAdapter,Handler detectedHandler){
this.mBtAdapter=mBtAdapter;
this.detectedHandler=detectedHandler;
}
public void connectBTServer(String address){
//check address is correct
if(BluetoothAdapter.checkBluetoothAddress(address)){
btdevice = mBtAdapter.getRemoteDevice(address);
ThreadPool.getInstance().excuteTask(new Runnable() {
public void run() {
try {
btsocket = btdevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
Message msg2 = new Message();
msg2.obj = "請(qǐng)稍候,正在連接服務(wù)器:"+BluetoothMsg.BlueToothAddress;
msg2.what = 0;
detectedHandler.sendMessage(msg2);
btsocket.connect();
Message msg = new Message();
msg.obj = "已經(jīng)連接上服務(wù)端!可以發(fā)送信息。";
msg.what = 0;
detectedHandler.sendMessage(msg);
receiverMessageTask();
} catch (IOException e) {
e.printStackTrace();
Log.e(Tag, e.getMessage());
Message msg = new Message();
msg.obj = "連接服務(wù)端異常!請(qǐng)檢查服務(wù)器是否正常,斷開連接重新試一試。";
msg.what = 0;
detectedHandler.sendMessage(msg);
}
}
});
}
}
private void receiverMessageTask(){
ThreadPool.getInstance().excuteTask(new Runnable() {
public void run() {
byte[] buffer = new byte[2048];
int totalRead;
/*InputStream input = null;
OutputStream output=null;*/
try {
bis=new BufferedInputStream(btsocket.getInputStream());
bos=new BufferedOutputStream(btsocket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
// ByteArrayOutputStream arrayOutput=null;
while((totalRead = bis.read(buffer)) > 0 ){
// arrayOutput=new ByteArrayOutputStream();
String txt = new String(buffer, 0, totalRead, "UTF-8");
Message msg = new Message();
msg.obj = "Receiver: "+txt;
msg.what = 1;
detectedHandler.sendMessage(msg);
}
} catch(EOFException e){
Message msg = new Message();
msg.obj = "server has close!";
msg.what = 1;
detectedHandler.sendMessage(msg);
}catch (IOException e) {
e.printStackTrace();
Message msg = new Message();
msg.obj = "receiver message error! make sure server is ok,and try again connect!";
msg.what = 1;
detectedHandler.sendMessage(msg);
}
}
});
}
public boolean sendmsg(String msg){
boolean result=false;
if(null==btsocket||bos==null)
return false;
try {
bos.write(msg.getBytes());
bos.flush();
result=true;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public void closeBTClient(){
try{
if(bis!=null)
bis.close();
if(bos!=null)
bos.close();
if(btsocket!=null)
btsocket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
聊天界面,使用上面分裝好的類,處理信息
package com.xiaoyu.communication;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import com.xiaoyu.bluetooth.BTClient;
import com.xiaoyu.bluetooth.BTManage;
import com.xiaoyu.bluetooth.BTServer;
import com.xiaoyu.bluetooth.BluetoothMsg;
public class BTChatActivity extends Activity {
private ListView mListView;
private Button sendButton;
private Button disconnectButton;
private EditText editMsgView;
private ArrayAdapter<String> mAdapter;
private List<String> msgList=new ArrayList<String>();
private BTClient client;
private BTServer server;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bt_chat);
initView();
}
private Handler detectedHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
msgList.add(msg.obj.toString());
mAdapter.notifyDataSetChanged();
mListView.setSelection(msgList.size() - 1);
};
};
private void initView() {
mAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, msgList);
mListView = (ListView) findViewById(R.id.list);
mListView.setAdapter(mAdapter);
mListView.setFastScrollEnabled(true);
editMsgView= (EditText)findViewById(R.id.MessageText);
editMsgView.clearFocus();
RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
// @Override
// public void onCheckedChanged(RadioGroup arg0, int arg1) {
// int radioId = arg0.getCheckedRadioButtonId();
//
// }
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radioNone:
BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.NONE;
if(null!=client){
client.closeBTClient();
client=null;
}
if(null!=server){
server.closeBTServer();
server=null;
}
break;
case R.id.radioClient:
BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.CILENT;
Intent it=new Intent(getApplicationContext(),BTDeviceActivity.class);
startActivityForResult(it, 100);
break;
case R.id.radioServer:
BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.SERVICE;
initConnecter();
break;
}
}
});
sendButton= (Button)findViewById(R.id.btn_msg_send);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String msgText =editMsgView.getText().toString();
if (msgText.length()>0) {
if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT){
if(null==client)
return;
if(client.sendmsg(msgText)){
Message msg = new Message();
msg.obj = "send: "+msgText;
msg.what = 1;
detectedHandler.sendMessage(msg);
}else{
Message msg = new Message();
msg.obj = "send fail!! ";
msg.what = 1;
detectedHandler.sendMessage(msg);
}
}
else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE) {
if(null==server)
return;
if(server.sendmsg(msgText)){
Message msg = new Message();
msg.obj = "send: "+msgText;
msg.what = 1;
detectedHandler.sendMessage(msg);
}else{
Message msg = new Message();
msg.obj = "send fail!! ";
msg.what = 1;
detectedHandler.sendMessage(msg);
}
}
editMsgView.setText("");
// editMsgView.clearFocus();
// //close InputMethodManager
// InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(editMsgView.getWindowToken(), 0);
}else{
Toast.makeText(getApplicationContext(), "發(fā)送內(nèi)容不能為空!", Toast.LENGTH_SHORT).show();
}
}
});
disconnectButton= (Button)findViewById(R.id.btn_disconnect);
disconnectButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT){
if(null==client)
return;
client.closeBTClient();
}
else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE) {
if(null==server)
return;
server.closeBTServer();
}
BluetoothMsg.isOpen = false;
BluetoothMsg.serviceOrCilent=BluetoothMsg.ServerOrCilent.NONE;
Toast.makeText(getApplicationContext(), "已斷開連接!", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
if (BluetoothMsg.isOpen) {
Toast.makeText(getApplicationContext(), "連接已經(jīng)打開,可以通信。如果要再建立連接,請(qǐng)先斷開!",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==100){
//從設(shè)備列表返回
initConnecter();
}
}
private void initConnecter(){
if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT) {
String address = BluetoothMsg.BlueToothAddress;
if (!TextUtils.isEmpty(address)) {
if(null==client)
client=new BTClient(BTManage.getInstance().getBtAdapter(), detectedHandler);
client.connectBTServer(address);
BluetoothMsg.isOpen = true;
} else {
Toast.makeText(getApplicationContext(), "address is empty please choose server address !",
Toast.LENGTH_SHORT).show();
}
} else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE) {
if(null==server)
server=new BTServer(BTManage.getInstance().getBtAdapter(), detectedHandler);
server.startBTServer();
BluetoothMsg.isOpen = true;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
client搜索設(shè)備列表,連接選擇server界面:
package com.xiaoyu.communication;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.xiaoyu.bluetooth.BTItem;
import com.xiaoyu.bluetooth.BTManage;
import com.xiaoyu.bluetooth.BluetoothMsg;
import com.xiaoyu.bluetooth.StatusBlueTooth;
public class BTDeviceActivity extends Activity implements OnItemClickListener
,View.OnClickListener ,StatusBlueTooth{
// private List<BTItem> mListDeviceBT=new ArrayList<BTItem>();
private ListView deviceListview;
private Button btserch;
private BTDeviceAdapter adapter;
private boolean hasregister=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finddevice);
setView();
BTManage.getInstance().setBlueListner(this);
}
private void setView(){
deviceListview=(ListView)findViewById(R.id.devicelist);
deviceListview.setOnItemClickListener(this);
adapter=new BTDeviceAdapter(getApplicationContext());
deviceListview.setAdapter(adapter);
deviceListview.setOnItemClickListener(this);
btserch=(Button)findViewById(R.id.start_seach);
btserch.setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
//注冊(cè)藍(lán)牙接收廣播
if(!hasregister){
hasregister=true;
BTManage.getInstance().registerBluetoothReceiver(getApplicationContext());
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
if(hasregister){
hasregister=false;
BTManage.getInstance().unregisterBluetooth(getApplicationContext());
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
final BTItem item=(BTItem)adapter.getItem(position);
AlertDialog.Builder dialog = new AlertDialog.Builder(this);// 定義一個(gè)彈出框?qū)ο?
dialog.setTitle("Confirmed connecting device");
dialog.setMessage(item.getBuletoothName());
dialog.setPositiveButton("connect",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// btserch.setText("repeat search");
BTManage.getInstance().cancelScanDevice();
BluetoothMsg.BlueToothAddress=item.getBluetoothAddress();
if(BluetoothMsg.lastblueToothAddress!=BluetoothMsg.BlueToothAddress){
BluetoothMsg.lastblueToothAddress=BluetoothMsg.BlueToothAddress;
}
setResult(100);
finish();
}
});
dialog.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
BluetoothMsg.BlueToothAddress = null;
}
});
dialog.show();
}
@Override
public void onClick(View v) {
BTManage.getInstance().openBluetooth(this);
if(BTManage.getInstance().isDiscovering()){
BTManage.getInstance().cancelScanDevice();
btserch.setText("start search");
}else{
BTManage.getInstance().scanDevice();
btserch.setText("stop search");
}
}
@Override
public void BTDeviceSearchStatus(int resultCode) {
switch(resultCode){
case StatusBlueTooth.SEARCH_START:
adapter.clearData();
adapter.addDataModel(BTManage.getInstance().getPairBluetoothItem());
break;
case StatusBlueTooth.SEARCH_END:
break;
}
}
@Override
public void BTSearchFindItem(BTItem item) {
adapter.addDataModel(item);
}
@Override
public void BTConnectStatus(int result) {
}
}
搜索列表adapter:
package com.xiaoyu.communication;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.xiaoyu.bluetooth.BTItem;
public class BTDeviceAdapter extends BaseAdapter{
private List<BTItem> mListItem=new ArrayList<BTItem>();;
private Context mcontext=null;
private LayoutInflater mInflater=null;
public BTDeviceAdapter(Context context){
this.mcontext=context;
// this.mListItem=mListItem;
this.mInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
void clearData(){
mListItem.clear();
}
void addDataModel(List<BTItem> itemList){
if(itemList==null || itemList.size()==0)
return;
mListItem.addAll(itemList);
notifyDataSetChanged();
}
void addDataModel(BTItem item){
mListItem.add(item);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mListItem.size();
}
@Override
public Object getItem(int position) {
return mListItem.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
if(convertView==null){
holder=new ViewHolder();
convertView = mInflater.inflate(R.layout.device_item_row, null);
holder.tv=(TextView)convertView.findViewById(R.id.itemText);
convertView.setTag(holder);
}else{
holder=(ViewHolder)convertView.getTag();
}
holder.tv.setText(mListItem.get(position).getBuletoothName());
return convertView;
}
class ViewHolder{
TextView tv;
}
}
列表model:
package com.xiaoyu.bluetooth;
public class BTItem {
private String buletoothName=null;
private String bluetoothAddress=null;
private int bluetoothType=-1;
public String getBuletoothName() {
return buletoothName;
}
public void setBuletoothName(String buletoothName) {
this.buletoothName = buletoothName;
}
public String getBluetoothAddress() {
return bluetoothAddress;
}
public void setBluetoothAddress(String bluetoothAddress) {
this.bluetoothAddress = bluetoothAddress;
}
public int getBluetoothType() {
return bluetoothType;
}
public void setBluetoothType(int bluetoothType) {
this.bluetoothType = bluetoothType;
}
}
使用到的輔助類:
package com.xiaoyu.bluetooth;
public class BluetoothMsg {
public enum ServerOrCilent{
NONE,
SERVICE,
CILENT
};
//藍(lán)牙連接方式
public static ServerOrCilent serviceOrCilent = ServerOrCilent.NONE;
//連接藍(lán)牙地址
public static String BlueToothAddress = null,lastblueToothAddress=null;
//通信線程是否開啟
public static boolean isOpen = false;
}
package com.xiaoyu.bluetooth;
public interface StatusBlueTooth {
final static int SEARCH_START=110;
final static int SEARCH_END=112;
final static int serverCreateSuccess=211;
final static int serverCreateFail=212;
final static int clientCreateSuccess=221;
final static int clientCreateFail=222;
final static int connectLose=231;
void BTDeviceSearchStatus(int resultCode);
void BTSearchFindItem(BTItem item);
void BTConnectStatus(int result);
}
package com.xiaoyu.utils;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPool {
private AtomicBoolean mStopped = new AtomicBoolean(Boolean.FALSE);
private ThreadPoolExecutor mQueue;
private final int coreSize=2;
private final int maxSize=10;
private final int timeOut=2;
private static ThreadPool pool=null;
private ThreadPool() {
mQueue = new ThreadPoolExecutor(coreSize, maxSize, timeOut, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), sThreadFactory);
// mQueue.allowCoreThreadTimeOut(true);
}
public static ThreadPool getInstance(){
if(null==pool)
pool=new ThreadPool();
return pool;
}
public void excuteTask(Runnable run) {
mQueue.execute(run);
}
public void closeThreadPool() {
if (!mStopped.get()) {
mQueue.shutdownNow();
mStopped.set(Boolean.TRUE);
}
}
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "ThreadPool #" + mCount.getAndIncrement());
}
};
}
最后別忘了加入權(quán)限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
在編程中遇到的問題:
Exception: Unable to start Service Discovery
java.io.IOException: Unable to start Service Discovery錯(cuò)誤
1、必須保證客戶端,服務(wù)器端中的UUID統(tǒng)一,客戶端格式為:UUID格式一般是"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
例如:UUID.fromString("81403000-13df-b000-7cf4-350b4a2110ee");
2、必須進(jìn)行配對(duì)處理后方可能夠連接
擴(kuò)展:藍(lán)牙后臺(tái)配對(duì)實(shí)現(xiàn)(網(wǎng)上看到的整理如下)
static public boolean createBond(Class btClass, BluetoothDevice btDevice)
throws Exception {
Method createBondMethod = btClass.getMethod("createBond");
Log.i("life", "createBondMethod = " + createBondMethod.getName());
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
static public boolean setPin(Class btClass, BluetoothDevice btDevice,
String str) throws Exception {
Boolean returnValue = null;
try {
Method removeBondMethod = btClass.getDeclaredMethod("setPin",
new Class[] { byte[].class });
returnValue = (Boolean) removeBondMethod.invoke(btDevice,
new Object[] { str.getBytes() });
Log.i("life", "returnValue = " + returnValue);
} catch (SecurityException e) {
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
} catch (IllegalArgumentException e) {
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnValue;
}
// 取消用戶輸入
static public boolean cancelPairingUserInput(Class btClass,
BluetoothDevice device) throws Exception {
Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
// cancelBondProcess()
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
Log.i("life", "cancelPairingUserInputreturnValue = " + returnValue);
return returnValue.booleanValue();
}
然后監(jiān)聽藍(lán)牙配對(duì)的廣播 匹配“android.bluetooth.device.action.PAIRING_REQUEST”這個(gè)action
然后調(diào)用上面的setPin(mDevice.getClass(), mDevice, "1234"); // 手機(jī)和藍(lán)牙采集器配對(duì)
createBond(mDevice.getClass(), mDevice);
cancelPairingUserInput(mDevice.getClass(), mDevice);
mDevice是你要去連接的那個(gè)藍(lán)牙的對(duì)象,1234為配對(duì)的pin碼
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android藍(lán)牙開發(fā)深入解析
- android實(shí)現(xiàn)藍(lán)牙文件發(fā)送的實(shí)例代碼,支持多種機(jī)型
- Android Bluetooth藍(lán)牙技術(shù)使用流程詳解
- Android編程之藍(lán)牙測(cè)試實(shí)例
- Android單片機(jī)與藍(lán)牙模塊通信實(shí)例代碼
- Android提高之藍(lán)牙傳感應(yīng)用實(shí)例
- Android系統(tǒng)中的藍(lán)牙連接程序編寫實(shí)例教程
- Android 藍(lán)牙2.0的使用方法詳解
- Android開發(fā)中編寫藍(lán)牙相關(guān)功能的核心代碼講解
- Android藍(lán)牙通信聊天實(shí)現(xiàn)發(fā)送和接受功能
- Android設(shè)備間實(shí)現(xiàn)藍(lán)牙(Bluetooth)共享上網(wǎng)
- Android 藍(lán)牙開發(fā)實(shí)例解析
- Android實(shí)現(xiàn)的簡(jiǎn)單藍(lán)牙程序示例
相關(guān)文章
Android 中Volley二次封裝并實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求緩存
這篇文章主要介紹了Android 中Volley二次封裝并實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求緩存的相關(guān)資料,希望通過本文能幫助到大家,徹底會(huì)使用Volley,需要的朋友可以參考下2017-09-09
Android EditTextView 實(shí)現(xiàn)帶空格分隔的輸入(電話號(hào)碼,銀行卡)
這篇文章主要介紹了Android EditTextView 實(shí)現(xiàn)帶空格分隔的輸入(電話號(hào)碼,銀行卡)的相關(guān)資料,需要的朋友可以參考下2018-02-02
Android ListView中headerview的動(dòng)態(tài)顯示和隱藏的實(shí)現(xiàn)方法
這篇文章主要介紹了Android ListView中headerview的動(dòng)態(tài)顯示和隱藏的實(shí)現(xiàn)方法的相關(guān)資料,這里提供兩種方法幫助實(shí)現(xiàn)這樣的功能,需要的朋友可以參考下2017-08-08
Flutter學(xué)習(xí)之構(gòu)建、布局及繪制三部曲
這篇文章主要給大家介紹了關(guān)于Flutter學(xué)習(xí)之構(gòu)建、布局及繪制三部曲的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Flutter具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
用Kotlin實(shí)現(xiàn)Android點(diǎn)擊事件的方法
本篇文章主要介紹了用Kotlin實(shí)現(xiàn)Android點(diǎn)擊事件的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
SwipeRefreshLayout+RecyclerView實(shí)現(xiàn)上拉刷新和下拉刷新功能
這篇文章主要介紹了SwipeRefreshLayout+RecyclerView實(shí)現(xiàn)上拉刷新和下拉刷新功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
Android沉浸式狀態(tài)欄實(shí)現(xiàn)示例
本篇文章主要介紹了Android沉浸式狀態(tài)欄實(shí)現(xiàn)示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02

