package com.example.adnroidtest;
import java.util.Iterator;
import java.util.Set;import android.app.Activity;
import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity {
private Button button;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button) this.findViewById(R.id.button1); button.setOnClickListener(new MyButton()); }class MyButton implements View.OnClickListener{
@Override
public void onClick(View v) { BluetoothAdapter adapeter=BluetoothAdapter.getDefaultAdapter(); if(adapeter!=null){ Toast.makeText(MainActivity.this,"手机发现蓝牙",Toast.LENGTH_LONG).show(); if (!adapeter.isEnabled()){ MainActivity.this.startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)); } Set<BluetoothDevice> device=adapeter.getBondedDevices(); if (device.size()>0){ Iterator iterator=device.iterator(); while (iterator.hasNext()){ BluetoothDevice model= (BluetoothDevice) iterator.next(); Toast.makeText(MainActivity.this,""+model.getAddress(),Toast.LENGTH_LONG).show(); } } }else{ Toast.makeText(MainActivity.this,"蓝牙未发现",Toast.LENGTH_LONG).show(); } } }@Override
public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }}