首先xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.zpj.aaa.bluetoothe.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bt" android:text="扫描设备" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> </RelativeLayout>实现过程
public class MainActivity extends AppCompatActivity { private Button button = null; private Button dis = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.bt); //扫描蓝牙的button 属性设置 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
//设置适配器 用一个Bluetoothadapter中的一个方法defaultadapter来生成一个个适配器 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
//p判断是否这个适配器为空。 即表示这台机器有无蓝牙设备 if(adapter !=null){ Log.e("SSS","I have blueteeth");
//可达的话就开启一个系统的intent if (adapter.isEnabled()){ Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(intent); }
//以前已经连接过的设备
远程的设备 Set<BluetoothDevice> devices = adapter.getBondedDevices(); if (devices.size()>0){ for (Iterator iterator = devices.iterator();iterator.hasNext();); { Iterator iterator = new Iterator() { @Override public boolean hasNext() { return false; } @Override public Object next() { return null; } @Override public void remove() { } };
//得到远程蓝牙的名字或者是别的属性 BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator.next(); Log.e("aga",bluetoothDevice.getName()); } } } else { Log.e("sss","no find"); } } }); } }