ANDROID_MARS学习笔记_S03_002_设置可见性及扫描蓝牙设备
一、代码
1.xml
(1)AndroidManifest.xml
1 <uses-permission android:name="android.permission.BLUETOOTH"/> 2 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 3 </manifest>
2.java
(1)MainActivity.java
1 package com.bluetooth2; 2 3 import android.app.Activity; 4 import android.bluetooth.BluetoothAdapter; 5 import android.bluetooth.BluetoothDevice; 6 import android.content.BroadcastReceiver; 7 import android.content.Context; 8 import android.content.Intent; 9 import android.content.IntentFilter; 10 import android.os.Bundle; 11 import android.view.View; 12 import android.view.View.OnClickListener; 13 import android.widget.Button; 14 15 public class MainActivity extends Activity { 16 17 private Button discoverButton = null; 18 private Button scanButton = null; 19 private BluetoothAdapter adapter = null; 20 private BluetoothReceiver bluetoothReceiver = null; 21 22 @Override 23 protected void onCreate(Bundle savedInstanceState) { 24 super.onCreate(savedInstanceState); 25 setContentView(R.layout.activity_main); 26 27 adapter = BluetoothAdapter.getDefaultAdapter(); 28 29 discoverButton = (Button) findViewById(R.id.discoverButton); 30 scanButton = (Button) findViewById(R.id.scanButton); 31 32 discoverButton.setOnClickListener(new OnClickListener() { 33 @Override 34 public void onClick(View v) { 35 Intent discoverIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 36 //设置蓝牙可见性,500表示可见时间(单位:秒),当值大于300时默认为300 37 discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500); 38 System.out.println("设置蓝牙可见性-->"); 39 startActivity(discoverIntent);//android自带的activity 40 } 41 }); 42 43 scanButton.setOnClickListener(new OnClickListener() { 44 @Override 45 public void onClick(View v) { 46 //开始扫描周围蓝牙设备,该方法是异步调用并以广播的机制返回,所以需要创建一个BroadcastReceiver来获取信息 47 System.out.println("开始扫描周围蓝牙设备-->"); 48 adapter.startDiscovery(); 49 } 50 }); 51 52 //设定广播接收的filter 53 IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 54 //创建蓝牙广播信息的receiver 55 bluetoothReceiver = new BluetoothReceiver(); 56 //注册广播接收器 57 registerReceiver(bluetoothReceiver, intentFilter); 58 } 59 60 private class BluetoothReceiver extends BroadcastReceiver { 61 @Override 62 public void onReceive(Context context, Intent intent) { 63 //获得扫描到的远程蓝牙设备 64 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 65 System.out.println("BluetoothReceiver收到广播---->" + device); 66 } 67 } 68 }
You can do anything you set your mind to, man!