关于设置蓝牙的可见性和扫描周围蓝牙设备的方法,需要用到广播接收器
package tjj.bluetooth2; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.widget.Button; public class TestBlueTooth2Activity extends Activity { private BluetoothAdapter bluetoothadapter; private Button scanbutton; private Button discoverbutton; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); discoverbutton = (Button) findViewById(R.id.button1); scanbutton = (Button) findViewById(R.id.button2); discoverbutton.setOnClickListener(DiscoverButtonListener); scanbutton.setOnClickListener(ScanButtonListener); //得到一个代表本地蓝牙设备的bluetoothadapter bluetoothadapter = BluetoothAdapter.getDefaultAdapter(); //设置一个过滤器,将action设置为BluetoothDevice.ACTION_FOUND IntentFilter intentfilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); //得到一个关于蓝牙的广播接收器 BluetoothReceiver bluetoothreceiver = new BluetoothReceiver(); //将广播接收器和过滤器注册起来 registerReceiver(bluetoothreceiver, intentfilter); } private Button.OnClickListener DiscoverButtonListener = new Button.OnClickListener() { public void onClick(View v) { //設置可見性 Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //设置可见时间 discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500); //打开的Activity是android自带的一个 startActivity(discoverableIntent); } }; private Button.OnClickListener ScanButtonListener = new Button.OnClickListener() { public void onClick(View v) { //开始扫描周围的蓝牙设备,一次最少12秒,每扫描到一个蓝牙设备,就会发送一个广播,因此需要一个过滤器和广播接收器 bluetoothadapter.startDiscovery(); } }; } class BluetoothReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { //能够通过这个过滤器的,它的action一定为我们需要的 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println(device.getAddress()); } }