之前写的博客都被移除了,也不知道什么原因,可能是字体太少了,我不喜欢怎么说,直接上源码比较好一点

我相信程序员都这样,除非代码难懂就会去解说一下,

先看下效果图:

 

 

看下java代码

public class MainActivity extends Activity {

	private ListView lv;
	private BluetoothAdapter adapter;
	private MyReciver myReciver;
	private ArrayList<String> list;
	private ArrayAdapter<String> adapters;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		lv = (ListView) findViewById(R.id.lv);
		
		//2、得到适配器		
		adapter = BluetoothAdapter.getDefaultAdapter();
		list = new ArrayList<String>();
		adapters = new ArrayAdapter<String>(
				this,
				android.R.layout.simple_list_item_1,
				android.R.id.text1,
				list);
		lv.setAdapter(adapters);
		
	}
	
	public void da(View view){
		//3、打开蓝牙-----两种方式:调用系统方式2、强行打开
		if(!adapter.isEnabled()){//判断是否打开
			Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//请求被发现
			startActivityForResult(intent, 100);//打开会返回资源
		}
//		if(!adapter.isEnabled()){
//			adapter.enable();//强行打开
//		}
		//4、设置可见
		Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//设置可见
		intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//秒
		startActivity(intent);
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==Activity.RESULT_OK){
			Toast.makeText(this, "已经打开", 0).show();
		}else{
			Toast.makeText(this, "失败", 0).show();
		}
	}
	
	public void sao(View view){
		list.clear();
		//5、扫描蓝牙
		IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		myReciver = new MyReciver();
		registerReceiver(myReciver, intentFilter);
		//开始扫描
		adapter.startDiscovery();
	}
	
	public void guan(View view){
		if(adapter.isEnabled()){
			adapter.disable();//关闭蓝牙
		}
	}
	public void cha(View view){
		//得到已经配对的
		Set<BluetoothDevice> devices = adapter.getBondedDevices();
		list.clear();
		for (BluetoothDevice bluetoothDevice : devices) {
			list.add(bluetoothDevice.getName()+"\n"+bluetoothDevice.getAddress());
			adapters.notifyDataSetChanged();	
		}
	}
	
	class MyReciver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			// 当系统发现设备就发送一次广播,接收广播,得到该蓝牙设备
			BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			if(!list.contains(device.getName()+"\n"+device.getAddress())){
				list.add(device.getName()+"\n"+device.getAddress());
				adapters.notifyDataSetChanged();				
			}
		}
		
	}
}

  上面的基本都有注释,不懂的可以联系我

使用蓝牙是需要权限的

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

 

posted on 2015-01-04 17:58  Striver_zw  阅读(291)  评论(0编辑  收藏  举报