public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final int REQUEST_ENABLE_BT = 1; private BluetoothAdapter defaultAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控件 findViewById(R.id.mButton01).setOnClickListener(this); findViewById(R.id.mButton02).setOnClickListener(this); // defaultAdapter = BluetoothAdapter.getDefaultAdapter(); } @Override protected void onResume() { super.onResume(); } //点击事件 @Override public void onClick(View v) { switch (v.getId()) { //开启蓝牙 case R.id.mButton01: defaultAdapter.enable(); if (defaultAdapter == null || !defaultAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, REQUEST_ENABLE_BT); } break; //关闭蓝牙 case R.id.mButton02: defaultAdapter.disable(); break; } } @Override public void onActivityReenter(int resultCode, Intent data) { super.onActivityReenter(resultCode, data); if (data == null) { return; } Toast.makeText(this, "蓝牙已启用", Toast.LENGTH_SHORT).show(); } }
Android中打开关闭蓝牙简单方法
最新推荐文章于 2024-07-18 01:36:53 发布