package com.partner.bluttooth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.Activity;
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.util.Log;
import android.util.Xml.Encoding;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class BlueToothTestActivity extends Activity {
// 该UUID表示串口服务
// 请参考文章<A
// href="http://wiley.iteye.com/blog/1179417">[url]http://wiley.iteye.com/blog/1179417<[/url];/A>
static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
Button btnSearch, btnDis, btnExit, btnConnect, btnSendData;
ToggleButton tbtnSwitch;
ListView lvBTDevices;
TextView txtConnectok;
ArrayAdapter<String> adtDevices;
List<String> lstDevices = new ArrayList<String>();
BluetoothAdapter btAdapt;
public static BluetoothSocket btSocket;
private String btName;// 蓝牙名称
public static final String ACTION_SCAN_MODE_CHANGED = "android.bluetooth.adapter.action.SCAN_MODE_CHANGED";
EditText editSendData;
// //////////////////////////////////////
private PrintStream mPrintStream = null;
private BufferedReader mBufferedReader = null;
private OutputStream os;//输出流给远程发送数据
// ///////////////////////////////////////
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button 设置
btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new ClickEvent());
btnExit = (Button) this.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new ClickEvent());
btnDis = (Button) this.findViewById(R.id.btnDis);
btnDis.setOnClickListener(new ClickEvent());
btnConnect = (Button) this.findViewById(R.id.btnConnect);
btnConnect.setOnClickListener(new ClickEvent());
editSendData = (EditText) this.findViewById(R.id.editSendData);
// 发送数据
btnSendData = (Button) this.findViewById(R.id.btnSendData);
btnSendData.setOnClickListener(new ClickEvent());
// ToogleButton设置
tbtnSwitch = (ToggleButton) this.findViewById(R.id.tbtnSwitch);
tbtnSwitch.setOnClickListener(new ClickEvent());
txtConnectok = (TextView) this.findViewById(R.id.txtConnectok);
// ListView及其数据源 适配器
lvBTDevices = (ListView) this.findViewById(R.id.lvDevices);
adtDevices = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lstDevices);
lvBTDevices.setAdapter(adtDevices);
lvBTDevices.setOnItemClickListener(new ItemClickEvent());
btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
// ========================================================
// modified by wiley
if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 读取蓝牙状态并显示
tbtnSwitch.setChecked(false);
else if (btAdapt.getState() == BluetoothAdapter.STATE_ON)
tbtnSwitch.setChecked(true);
else if (btAdapt.getState() == BluetoothAdapter.STATE_TURNING_ON)
Toast.makeText(this, "start turning on 连接成功", 3000).show();
if (btAdapt.isEnabled()) {
tbtnSwitch.setChecked(false);
} else {
tbtnSwitch.setChecked(true);
}
// ============================================================
// 注册Receiver来获取蓝牙设备相关的结果
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intent);
}
private BroadcastReceiver searchDevices = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("action is >>>" + action);
Bundle b = intent.getExtras();
Object[] lstName = b.keySet().toArray();
// 显示所有收到的消息及其细节
for (int i = 0; i < lstName.length; i++) {
String keyName = lstName[i].toString();
Log.e(keyName, String.valueOf(b.get(keyName)));
}
BluetoothDevice device = null;
// 搜索设备时,取得设备的MAC地址
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
String str = "未配对|" + device.getName() + "|"
+ device.getAddress();
if (lstDevices.indexOf(str) == -1)// 防止重复添加
lstDevices.add(str); // 获取设备名称和mac地址
adtDevices.notifyDataSetChanged();
}
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
switch (device.getBondState()) {
case BluetoothDevice.BOND_BONDING:
Log.d("BlueToothTestActivity", "正在配对......");
Toast.makeText(BlueToothTestActivity.this, "开始配对", 3000)
.show();
break;
case BluetoothDevice.BOND_BONDED:
Log.d("BlueToothTestActivity", "完成配对");
connect(device);// 连接设备
break;
case BluetoothDevice.BOND_NONE:
Log.d("BlueToothTestActivity", "取消配对");
default:
break;
}
}
// ////////////////////////////
else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
Toast.makeText(BlueToothTestActivity.this, "else if 连接成功",
3000).show();
}
}
};
@Override
protected void onDestroy() {
this.unregisterReceiver(searchDevices);
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
// //////////////////////////////////////////////////
// //////////////////////////////////////////////////
class ItemClickEvent implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (btAdapt.isDiscovering())
btAdapt.cancelDiscovery();
String str = lstDevices.get(arg2);
String[] values = str.split("\\|");
String address = values[2];
Log.e("address", values[2]);
BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
try {
Boolean returnValue = false;
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
// 利用反射方法调用BluetoothDevice.createBond(BluetoothDevice
// remoteDevice);
Method createBondMethod = BluetoothDevice.class
.getMethod("createBond");
Log.d("BlueToothTestActivity", "开始配对");
Toast.makeText(BlueToothTestActivity.this, "开始配对", 3000)
.show();
returnValue = (Boolean) createBondMethod.invoke(btDev);
} else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) {
Toast.makeText(BlueToothTestActivity.this, "正在开始连接", 3000)
.show();
connect(btDev);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 服务器端
private void serviceConnect() throws IOException {
UUID uuid = UUID.fromString(SPP_UUID);
BluetoothServerSocket serverSocket = btAdapt
.listenUsingRfcommWithServiceRecord("MyBluetoothApp", uuid);
BluetoothSocket socket = serverSocket.accept();
}
// 连接设备
private void connect(BluetoothDevice btDev) {
UUID uuid = UUID.fromString(SPP_UUID);
Method m = null;
try {
try {
m = btDev.getClass().getMet
kangpanpan1
- 粉丝: 0
- 资源: 5
最新资源
- (源码)基于Redis和Elasticsearch的日志与指标处理系统.zip
- 学习记录111111111111111111111111
- (源码)基于Python和Selenium的jksb系统健康申报助手.zip
- (源码)基于HiEasyX库的学习工具系统.zip
- (源码)基于JSP+Servlet+JDBC的学生宿舍管理系统.zip
- (源码)基于Arduino和Raspberry Pi的自动化花园系统.zip
- (源码)基于JSP和Servlet的数据库管理系统.zip
- (源码)基于Python的文本相似度计算系统.zip
- (源码)基于Spring Boot和Redis的高并发秒杀系统.zip
- (源码)基于Java的Web汽车销售管理系统.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
- 1
- 2
- 3
前往页