Android蓝牙----打开,关闭操作
① 我们先在AndroidManifest里面增加我们的Bluetooth权限
<uses-permission android:name="android.permission.BLUETOOTH"/> //使用蓝牙所需要的权限
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> //使用扫描和设置蓝牙的权限(申明这一个权限必须申明上面一个权限)
② 写个简单的布局文件
1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context="com.example.administrator.bluetoothdemo.MainActivity"> 8 9 10 <Button 11 android:id="@+id/Btn1" 12 android:layout_width="wrap_content" 13 android:layout_height="wrap_content" 14 android:layout_alignParentTop="true" 15 android:layout_centerHorizontal="true" 16 android:layout_marginTop="53dp" 17 android:text="open Bluetooth" 18 android:textAllCaps="false" 19 /> 20 <Button 21 android:id="@+id/Btn2" 22 android:layout_width="wrap_content" 23 android:layout_height="wrap_content" 24 android:layout_alignParentTop="true" 25 android:layout_centerHorizontal="true" 26 android:layout_marginTop="100dp" 27 android:text="clase Bluetooth" 28 android:textAllCaps="false" 29 /> 30 </RelativeLayout>
③ 接下来写MainActivity类的代码
1 package com.example.administrator.bluetoothdemo; 2 3 import android.bluetooth.BluetoothAdapter; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8 import android.widget.Toast; 9 10 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 11 12 private Button mBtn,mBtn1; 13 private BluetoothAdapter mBluetooth; 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.activity_main); 18 findView(); //查找控件 19 mBtn.setOnClickListener(this); //创建点击事件 20 mBtn1.setOnClickListener(this); 21 } 22 public void onClick(View v) 23 { 24 switch(v.getId()) 25 { 26 case R.id.Btn1: 27 { 28 if(!mBluetooth.isEnabled()) 29 { 30 mBluetooth.enable(); 31 } 32 Toast.makeText(MainActivity.this,"打开成功", Toast.LENGTH_SHORT).show(); 33 }break; 34 35 case R.id.Btn2: 36 { 37 if(mBluetooth.isEnabled()) 38 { 39 mBluetooth.disable(); 40 } 41 Toast.makeText(MainActivity.this,"关闭成功", Toast.LENGTH_SHORT).show(); 42 }break; 43 } 44 } 45 public void findView() 46 { 47 mBtn = (Button)findViewById(R.id.Btn1); 48 mBtn1 = (Button) findViewById(R.id.Btn2); 49 mBluetooth = BluetoothAdapter.getDefaultAdapter(); //获取Bluetooth适配器 50 } 51 }