package com.example.weijiqian.bluetooth;
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.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
Button open;
Button close;
Button listBtn;
ListView listview;
Button search;
/**
* 设备列表
*/
ArrayList deviceList;
ArrayAdapter adapter;
/**
* //已经配对的设备
*/
Set<BluetoothDevice> deviceSet;
/**
* 蓝牙适配器
*/
BluetoothAdapter bluetoothAdapter;
/**
* UUID,是随便写的,两个配对的设备UUID要是一样的.
*/
private final UUID MY_UUID = UUID.fromString("e220ff28-b64a-4cbc-804b-a73dfcdc3941");
private final String NAME = "bluetoothSocket";
/**
* 蓝牙客户端
*/
private BluetoothSocket clientSocket;
/**
* 蓝牙设备
*/
private BluetoothDevice device;
/**
* 输出流
*/
private OutputStream ous;
/**
* 线程,接受传递过来的数据.
*/
private AcceptThread acceptThread ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
open = (Button) findViewById(R.id.open);
close = (Button) findViewById(R.id.close);
listBtn = (Button) findViewById(R.id.show_list);
search = (Button) findViewById(R.id.search);
listview = (ListView) findViewById(R.id.list_view);
//实例化蓝牙
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//初始化蓝牙列表显示.
deviceList = new ArrayList();
adapter = new ArrayAdapter
(this,android.R.layout.simple_list_item_1, deviceList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
//注册广播,接受扫描附近蓝牙的结果.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
//开启线程.监听数据.
acceptThread = new AcceptThread();
acceptThread.start();
open.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openBluetooth();
}
});
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchBluetooth();
}
});
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
closeBluetooth();
}
});
listBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showList();
}
});
}
private void openBluetooth() {
//打开蓝牙
if(!bluetoothAdapter.isEnabled()){
//弹出对话框提示用户是后打开
Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler, 0);
Toast.makeText(MainActivity.this,"打开蓝牙",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this,"蓝牙已经打开",Toast.LENGTH_LONG).show();
}
//打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)
startActivityForResult(discoveryIntent,0);
}
private void searchBluetooth() {
if ( !bluetoothAdapter.isDiscovering()){
deviceList.clear();
bluetoothAdapter.startDiscovery();
Toast.makeText(MainActivity.this,"蓝牙开始扫描",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this,"蓝牙正在扫描",Toast.LENGTH_LONG).show();
}
}
private void showList() {
//已经配对的设备
deviceSet = bluetoothAdapter.getBondedDevices();
deviceList.clear();
for(BluetoothDevice bt : deviceSet)
deviceList.add(bt.getName() +":"+bt.getAddress());
adapter.notifyDataSetChanged();
}
private void closeBluetooth() {
if (bluetoothAdapter.isEnabled()){
bluetoothAdapter.disable();
}
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//找到设备.搜索附近的设备.
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(MainActivity.this,"搜索到设备",Toast.LENGTH_LONG).show();
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
Log.e("dddd", "find device:" + device.getName()
+ device.getAddress());
deviceList.add(device.getName()+":"+ device.getAddress());
adapter.notifyDataSetChanged();
}
}
//搜索完成
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
Toast.makeText(MainActivity.this,"搜索完成",Toast.LENGTH_LONG).show();
}
}
};
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//点击配对.
//客户端
String s =(String) adapter.getItem(position);
String address = s.substring(s.indexOf(":")+1).trim();
try{
Log.e("ddd","开始配对");
if (bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
if (device == null ){
device = bluetoothAdapter.getRemoteDevice(address);
}
if (clientSocket == null ){
clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
clientSocket.connect();
}
//得到输出流
ous = clientSocket.getOutputStream();
//把数据放到输出流.
if (ous != null ){
ous.write("发送数据到另外一个手机".getBytes("utf-8"));
}
}catch (Exception e){
Log.e("ddd","连接出错:"+e.getMessage());
}
}
//服务端
private Handler handle = new Handler(){