package syd.myapplicationbluetooth; 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.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private BluetoothAdapter bluetoothAdapter; private ListView listview; private List<String> stringList=new ArrayList<>(); private ArrayAdapter<String> arrayAdapter; private UUID MYUUID=UUID.fromString("550E8400-E29B-11D4-A716-446655440000");//8-4-4-4-12,十六进制 private BluetoothServerSocket bluetoothServerSocket; private BluetoothSocket bluetoothSocket; private OutputStream os; private InputStream is; private final String NAME = "Bluetooth_Socket"; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview= (ListView) findViewById(R.id.listview); editText= (EditText) findViewById(R.id.edtext); arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stringList); listview.setAdapter(arrayAdapter); listview.setOnItemClickListener(this); bluetoothAdapter=BluetoothAdapter.getDefaultAdapter(); //每一个设备被找到,每找到一个设备会发送一次广播 IntentFilter intentFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND); //注册接收器 this.registerReceiver(myreceive,intentFilter); //搜索完毕后发送广播 IntentFilter intentFilter1=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(myreceive,intentFilter1); //获取之前配过对的蓝牙 Set<BluetoothDevice> bluetoothdevice=bluetoothAdapter.getBondedDevices(); System.out.println(bluetoothdevice.size()); if (bluetoothdevice.size()>0){ for (BluetoothDevice bounddevice:bluetoothdevice ) { String ds=bounddevice.getName() + ":" + bounddevice.getAddress(); System.out.println(ds); stringList.add(ds); } } findViewById(R.id.btnopenbluetooth).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent,1);*/ /* BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!bluetoothAdapter.isEnabled()) bluetoothAdapter.enable();*/ // bluetoothAdapter.disable();searchBlueTooth searchBlueTooth(); } }); try { AcceptThread acceptThread=new AcceptThread(); acceptThread.start(); } catch (IOException e) { e.printStackTrace(); } findViewById(R.id.btnsend).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (os!=null){ try { os.write(editText.getText().toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } } }); } private void searchBlueTooth() { //搜索方法不能调用两次 // TODO: 2015/10/17 /* setProgressBarIndeterminateVisibility(true); setProgressBarIndeterminate(true);*/ setTitle("正在搜索....."); if (bluetoothAdapter.isDiscovering()){ System.out.println("______________________"); bluetoothAdapter.cancelDiscovery(); } bluetoothAdapter.startDiscovery();//此语句是异步的,执行后会立即执行后面的语句 } private final BroadcastReceiver myreceive=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()){ case BluetoothDevice.ACTION_FOUND://搜到一个已绑定的蓝牙 System.out.println("================"); BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState()!=BluetoothDevice.BOND_BONDED){ stringList.add(device.getName()+":"+device.getAddress()); } break; case BluetoothAdapter.ACTION_DISCOVERY_FINISHED://搜索完毕 /* setProgressBarIndeterminate(false); setProgressBarIndeterminateVisibility(false);*/ setTitle("已经搜索完成"); break; } } }; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String s=stringList.get(position); //获取地址,相当于网络的ip String address=s.substring(s.indexOf(":")+1).trim();//吧空格戒掉 BluetoothDevice device=bluetoothAdapter.getRemoteDevice(address); if (bluetoothAdapter.isDiscovering()){ bluetoothAdapter.cancelDiscovery(); } if (device!=null){ try { bluetoothSocket=device.createRfcommSocketToServiceRecord(MYUUID); bluetoothSocket.connect(); os=bluetoothSocket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } } } Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); String message=msg.obj.toString(); Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show(); Toast.makeText(MainActivity.this,"djh",Toast.LENGTH_LONG).show(); } }; private class AcceptThread extends Thread{ private BluetoothServerSocket bluetoothServerSocket01; private BluetoothSocket bluetoothSocket01; public AcceptThread() throws IOException { bluetoothServerSocket01=bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME,MYUUID); } @Override public void run() { try { bluetoothSocket01=bluetoothServerSocket01.accept(); is=bluetoothSocket01.getInputStream(); os=bluetoothSocket01.getOutputStream(); while (true){ byte[]bytes=new byte[1024]; int count=is.read(bytes); Message message=new Message(); message.obj=new String(bytes,0,count,"UTF-8"); if (count!=0) handler.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } }}
//权限
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <!-- <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>-->
安卓蓝牙通信
最新推荐文章于 2024-04-27 16:52:58 发布