1 BluetoothAdapter 用法android
蓝牙运行原理:经过BluetoothAdapter 蓝牙适配器处理任务,若是蓝牙被启动以后,系统会自动去搜索其它设备,若是匹配到附近的设备就发送一个广播,BroadcastRecevier的onReceive被调用一次,咱们只须要在onReceive中处理本身的操做便可。服务器
蓝牙是一种支持设备短距离传输数据的无线技术。android在2.0之后提供了这方面的支持。 从查找蓝牙设备到可以相互通讯要通过几个基本步骤(本机作为服务器):app
1.在manifest中配置蓝牙操做的相关权限ide
2.启动蓝牙 首先要查看本机是否支持蓝牙,获取BluetoothAdapter蓝牙适配器对象对象
3 实现简单打开蓝牙事件
注意必须添加权限:<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> get
package com.example.administrator.blutooth; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private Button btn_open, btn_close; private TextView txt_name, txt_other; private BluetoothAdapter blutooth; //打开标志 private static int CODE_OPEN=100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); InitView(); InitBlutooth(); Listener(); } //初始化视图 public void InitView() { txt_name = findViewById(R.id.bt_name); txt_other = findViewById(R.id.bt_con); btn_close = findViewById(R.id.btn_close); btn_open = findViewById(R.id.btn_open); } //事件监听 public void Listener() { btn_open.setOnClickListener(oncliklistener); btn_close.setOnClickListener(oncliklistener); } //初始化蓝牙 public void InitBlutooth() { blutooth=BluetoothAdapter.getDefaultAdapter(); } //事件处理 View.OnClickListener oncliklistener = new View.OnClickListener() { @Override public void onClick(View v) { //是否支持蓝牙 if (blutooth != null) { txt_name.setText(blutooth.getName()); txt_other.setText(blutooth.getAddress()); switch (v.getId()) { case R.id.btn_close: blutooth.disable(); break; case R.id.btn_open: OpenBt(); break; } } } }; //打开蓝牙 public void OpenBt() { Intent openbt=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(openbt,CODE_OPEN); } //关闭蓝牙 public void CloseBt() { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(CODE_OPEN==requestCode) { Toast.makeText(getApplicationContext(),"蓝牙已经打开",Toast.LENGTH_SHORT); } } }