package com.bluetooth.uart;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class BluetoothUart{
static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
static final UUID uuid = UUID.fromString(SPP_UUID);
static final String tag = "BluetoothSPP";
static final boolean D = true;
ListView devList;
ArrayList<String> devices = new ArrayList<String>();
ArrayAdapter<String> devAdapter;
static public BluetoothAdapter btAdapt;
static public BluetoothSocket btSocket;
InputStream btIn = null;
OutputStream btOut;
Context context;
SppServer sppServer;
boolean sppConnected = false;
Handler handler1;
public void Seach(){
btAdapt.cancelDiscovery();
btAdapt.startDiscovery();
}
public void Write(String st) {
try {
btOut.write(st.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void Bluet_Init(Context context1,ListView listView,Handler handler){
context = context1;
devList = listView;
handler1= handler;
devAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, devices);
devList.setAdapter(devAdapter);
btAdapt = BluetoothAdapter.getDefaultAdapter();
/**/// 用BroadcastReceiver来取得搜索结果
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
context.registerReceiver(bluetoothReceiver, intent);
//搜到的蓝牙设备
devList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (sppConnected)
return;
// TODO Auto-generated method stub
String devAddr = ((String)devices.get(position)).split("/-/")[1];
try {
//创建SPP 的 RfcommSocket, SPP从机
btSocket = btAdapt.getRemoteDevice(devAddr)
.createRfcommSocketToServiceRecord(uuid);
btSocket.connect();
synchronized (context) {
if (sppConnected)
return;
btServerSocket.close();
btIn = btSocket.getInputStream();
btOut = btSocket.getOutputStream();
conected();
}
/**
byte[] wr = new byte[]{1,2,3,4,5};
btOut.write(wr, 0, 5);
/**/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
sppConnected = false;
try {
btSocket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
btSocket = null;
Toast.makeText(context, "SPP连接出错", Toast.LENGTH_SHORT).show();
}
}
});
// SPP服务
sppServer = new SppServer();
sppServer.start();
}
public void onDestroy(){
if (sppServer != null)
sppServer.cancel();
context.unregisterReceiver(bluetoothReceiver);
if (btIn != null) {
try {
btSocket.close();
btServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
android.os.Process.killProcess(android.os.Process.myPid());
}
private void disconnect() {
devList.setClickable(true);
sppConnected = false;
btIn = null;
btOut = null;
sppServer = new SppServer();
sppServer.start();
}
private void conected() {
sppConnected = true;
new SppReceiver(btIn).start();
devList.setClickable(false);
sppServer = null;
}
private BluetoothServerSocket btServerSocket;
private class SppServer extends Thread {
public SppServer() {
try {
btServerSocket = btAdapt.listenUsingRfcommWithServiceRecord("SPP", uuid);
} catch (IOException e) {
e.printStackTrace();
btServerSocket = null;
}
}
public void run() {
BluetoothSocket bs = null;
if (btServerSocket == null) {
Log.e(tag, "ServerSocket null");
return;
}
try {
bs = btServerSocket.accept();
synchronized (context) {
if (sppConnected)
return;
Log.i(tag, "Devices Name: " + bs.getRemoteDevice().getName());
btIn = bs.getInputStream();
btOut = bs.getOutputStream();
conected();
}
} catch (IOException e) {
e.printStackTrace();
Log.d(tag, "ServerSoket accept failed");
}
if (D) Log.i(tag, "End Bluetooth SPP Server");
}
public void cancel() {
if (btServerSocket == null)
return;
try {
btServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(tag, "close ServerSocket failed");
}
}
}
private class SppReceiver extends Thread {
private InputStream input = null;
public SppReceiver(InputStream in) {
input = in;
Log.i(tag, "SppReceiver ");
}
public void run() {
byte[] data = new byte[1024];
int length = 0;
if (input == null) {
Log.d(tag, "InputStream null");
return;
}
while (true) {
if(input!=null){
try {
length = input.read(data);
msg = new String(data, 0, length, "ASCII");
System.out.println(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// try {
// length = input.read(data);
// if (length > 0) {
// int j=0;
// j++;
// if(j==1){
// j=0;
// msg = new String(data, 0, length, "ASCII");
// System.out.println(msg);
// Message message = new Message();
// message.obj = msg;
// message.what=1;
// handler1.sendMessage(message);
// }
//
// }
// } catch (IOException e) {
// Log.e(tag, "disconnect");
// disconnect();
// }
}
}
}
private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
Object[] lstName = b.keySet().toArray();
// 显示所有收到的消息及其细节
for (int i = 0; i < lstName.length; i++) {
String keyName = lstName[i].toString();
Log.i(keyName, String.valueOf(b.get(keyName)));
}
//搜索设备时,取得设备的MAC地址
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String str = device.getName() + "/-/" + device.getAddress();
if (devices.indexOf(str) == -1)// 防止重复添加
devices.add(str); // 获取设备名称和mac地址
devAdapter.notifyDataSetChanged();
} else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
}
}
};
private String msg = "";
}
不要忘记加上权限哟!
有APP源码有需要的同学可以下载看看
|
|