//本程序连接必须自己先在手机上与对方配对然后再运行这个程序....
public class BluetoothComActivity extends Activity {
/** Called when the activity is first created. */
private BluetoothDevice[] foundDevice = new BluetoothDevice[3];
private CharSequence[] DeviceName = new CharSequence[3];
BluetoothAdapter bAdapter ;
private int DISCOVERY_REQUEST = 1;
private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");//文件交换型UUID,
//需要其他类型的UUID就自己去查表,或者是服务器,客户端都是自己写,那有就你自己定一个公用的UUID
private BluetoothSocket bSocket;
private String bluetoothName ;
private String bluetoothAddress;
ArrayAdapter adapter;
ListView list;
int DeviceNum;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bAdapter = BluetoothAdapter.getDefaultAdapter();
//-------------开启蓝牙前准备---------------------
//-------------蓝牙状态广播接收器-------------------------------------
BroadcastReceiver bluetoothState = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String preStateExtra = BluetoothAdapter.EXTRA_PREVIOUS_STATE;
String stateExtra = BluetoothAdapter.EXTRA_STATE;
int state = intent.getIntExtra(stateExtra, -1);
int previousState = intent.getIntExtra(preStateExtra, -1);
switch(state){
case (BluetoothAdapter.STATE_TURNING_ON):
Toast.makeText(BluetoothComActivity.this,"Bluetooth trun on!", Toast.LENGTH_SHORT).show(); break;
case (BluetoothAdapter.STATE_ON):
Toast.makeText(BluetoothComActivity.this,"Bluetooth state on!", Toast.LENGTH_SHORT).show();
bluetoothName = bAdapter.getName();
bluetoothAddress = bAdapter.getAddress();
System.out.println(bluetoothName);
System.out.println(bluetoothAddress);
//---------开始扫描---------------------------------------------------------
bAdapter.startDiscovery();
break;
case (BluetoothAdapter.STATE_TURNING_OFF):
Toast.makeText(BluetoothComActivity.this,"Bluetooth state trun off!", Toast.LENGTH_SHORT).show(); break;
case (BluetoothAdapter.STATE_OFF):
Toast.makeText(BluetoothComActivity.this,"Bluetooth off!", Toast.LENGTH_SHORT).show(); break;
default: break;
}
}
};
//----------开启蓝牙-------------------------------------------------
if(!bAdapter.isEnabled()){
String actionStateChange = BluetoothAdapter.ACTION_STATE_CHANGED;
String actionStateEnable = BluetoothAdapter.ACTION_REQUEST_ENABLE;
registerReceiver(bluetoothState, new IntentFilter(actionStateChange));
startActivityForResult(new Intent(actionStateEnable), 0);
}
//while(!bAdapter.isEnabled());
//---------扫描蓝牙设备前准备(作为主机)------------------------------------------------
//String discoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
//startActivityForResult(new Intent(discoverable), DISCOVERY_REQUEST);
//---------扫描过程广播监听--------------------------------------------------
BroadcastReceiver discoveryReceiver = new BroadcastReceiver(){
String aStarted = BluetoothAdapter.ACTION_DISCOVERY_STARTED;
String aFinished= BluetoothAdapter.ACTION_DISCOVERY_FINISHED;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(aStarted.equals(intent.getAction())){
Toast.makeText(BluetoothComActivity.this,"Discovery Start......", Toast.LENGTH_SHORT).show();
System.out.println("开始扫描!");
}
if(aFinished.equals(intent.getAction())){
Toast.makeText(BluetoothComActivity.this,"Discovery Finish......", Toast.LENGTH_SHORT).show();
System.out.println("结束扫描!");
}
}
};
registerReceiver(discoveryReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(discoveryReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
//----------扫描结果广播监听------------------------------------------------------------------------------
BroadcastReceiver discoveryResult = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("配对成功!");
String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
System.out.println(remoteDeviceName);
BluetoothDevice remoteDevice ;
remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(remoteDevice);
foundDevice[DeviceNum] = remoteDevice;
DeviceName[DeviceNum] = remoteDeviceName;
DeviceNum++;
if(DeviceNum == 3) DeviceNum--;
//Toast.makeText(getApplicationContext(), "Discovered: "+remoteDeviceName, Toast.LENGTH_SHORT);
if(bAdapter.getBondedDevices().contains(remoteDevice)){
System.out.println("bond:"+remoteDeviceName);
}
adapter.notifyDataSetChanged();
}
};
registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
if(!bAdapter.isDiscovering()){
bAdapter.startDiscovery();
}
for(int i = 0 ; i < DeviceName.length;i++){
DeviceName[i] = (String)(" ");
}
list = (ListView)this.findViewById(R.id.listview);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1, DeviceName);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
ConnectBluetoothService(position);
}
});
}
//---------根据扫描结果进行绑定连接(作为从机)-------------------------------------------------------------------------
public void ConnectBluetoothService(int i){
try {
System.out.println("I am here!");
System.out.println(foundDevice[i].getName());
System.out.println(uuid);
BluetoothSocket bs = foundDevice[i].createRfcommSocketToServiceRecord(uuid);
if(bAdapter.isDiscovering()){
bAdapter.cancelDiscovery();
}
bs.connect();
if(bs!=null)
System.out.println("Connect!"); //输出这个表示连接成功
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("蓝牙连接错误");
}
}
//--------------------------------------------------------------------------------------------------------
/* //--------------------监听绑定连接(作为主机)-----------------------------------------------------------------------------------
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == DISCOVERY_REQUEST){
boolean isDiscoverable = requestCode > 0;
if(isDiscoverable){
String name = "bluetoothService";
try {
final BluetoothServerSocket bServerSocket = bAdapter.listenUsingRfcommWithServiceRecord(name, uuid);
AsyncTask<Integer,Void,BluetoothSocket> accpetThread = new AsyncTask<Integer, Void, BluetoothSocket>(){
@Override
protected BluetoothSocket doInBackground(
Integer... params) {
// TODO Auto-generated method stub
try {
bSocket = bServerSocket.accept();
return bSocket;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("蓝牙连接");
}
return null;
}
};
accpetThread.execute(resultCode);
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
bSocket = bServerSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("蓝牙连接错误");
}
}
}).start() ;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("蓝牙主机搭建错误");
}
}
}
}*/
}