Android 蓝牙

博客围绕蓝牙应用展开,涉及权限设置,还包含布局代码、Activity代码以及适配器代码等信息技术相关内容,展示了蓝牙应用在代码层面的实现。

蓝牙的应用

权限:

// An highlighted block
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

布局代码

// An highlighted block
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/main_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启蓝牙"
        />
    <Button
        android:id="@+id/main_stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="关闭蓝牙"
        />
    <Button
        android:id="@+id/main_serch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="搜索蓝牙"
        />

    <ListView
        android:id="@+id/main_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

Activity代码

// An highlighted block
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ListView listView;
    private Button start;
    private Button stop;
    private Button serch;
    private ArrayList<Bean> list = new ArrayList<>();
    private MyAdapter adapter;
    private String[] permssion = new String[]{Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.BLUETOOTH,Manifest.permission.ACCESS_COARSE_LOCATION};
    private boolean ispermission;
    private boolean isok;


    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothReceiver bluetoothReceiver;


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initpermission();
        initView();
        initData();


    }

    private void initpermission() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            for (String p: permssion) {
                if(checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED){
                    ispermission = true;
                }
            }

            if(ispermission){
                requestPermissions(permssion,500);
            }
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 500){
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    isok = true;
                }
            }
        }
    }

    public void initView(){
        listView = findViewById(R.id.main_list);
        start = findViewById(R.id.main_start);
        stop = findViewById(R.id.main_stop);
        serch = findViewById(R.id.main_serch);

        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        serch.setOnClickListener(this);

        adapter = new MyAdapter();
        listView.setAdapter(adapter);
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void initData(){
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        if(bluetoothAdapter == null){
            finish();
            return;
        }

        bluetoothReceiver = new BluetoothReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//可发现
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索结果
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//绑定状态

        registerReceiver(bluetoothReceiver,intentFilter);

    }

    @Override
    public void onClick(View v) {
          switch (v.getId()){
              case R.id.main_start:
                  boolean flag = bluetoothAdapter.enable();
                  if(!flag){
                      Intent intent = new Intent();
                      intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//启动蓝牙
                      intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//开启本设备可被发现
                      intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);//指定搜索时间,
                      startActivityForResult(intent,100);
                  }
                  break;
              case R.id.main_stop:
                  bluetoothAdapter.disable();//关闭蓝牙
                  list.clear();
                  adapter.refresh(list);
                  break;
              case R.id.main_serch:
                  bluetoothAdapter.startDiscovery();//开启搜索
                  break;
                  default:
                      break;
          }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100 ){

        }
    }

    private class BluetoothReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                   String action = intent.getAction();
                   switch (action){
                       case BluetoothDevice.ACTION_FOUND:
                           //搜索到一台蓝牙设备进入一次FOUND
                           //搜索到的设备保存到list中
                           BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                           Bean bean = new Bean();
                           bean.name = bluetoothDevice.getName();
                           bean.address = bluetoothDevice.getAddress();
                           bean.bluetoothDevice = bluetoothDevice;
                           Log.e("######",bluetoothDevice.getName());
                           list.add(bean);

                           adapter.refresh(list);
                           break;

                       case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:

                           adapter.refresh(list);
                           break;
                           default:
                               break;
                   }
        }
    }
}

适配器代码

// An highlighted block
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ListView listView;
    private Button start;
    private Button stop;
    private Button serch;
    private ArrayList<Bean> list = new ArrayList<>();
    private MyAdapter adapter;
    private String[] permssion = new String[]{Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.BLUETOOTH,Manifest.permission.ACCESS_COARSE_LOCATION};
    private boolean ispermission;
    private boolean isok;


    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothReceiver bluetoothReceiver;


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initpermission();
        initView();
        initData();


    }

    private void initpermission() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            for (String p: permssion) {
                if(checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED){
                    ispermission = true;
                }
            }

            if(ispermission){
                requestPermissions(permssion,500);
            }
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 500){
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    isok = true;
                }
            }
        }
    }

    public void initView(){
        listView = findViewById(R.id.main_list);
        start = findViewById(R.id.main_start);
        stop = findViewById(R.id.main_stop);
        serch = findViewById(R.id.main_serch);

        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        serch.setOnClickListener(this);

        adapter = new MyAdapter();
        listView.setAdapter(adapter);
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void initData(){
        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        if(bluetoothAdapter == null){
            finish();
            return;
        }

        bluetoothReceiver = new BluetoothReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//可发现
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索结果
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//绑定状态

        registerReceiver(bluetoothReceiver,intentFilter);

    }

    @Override
    public void onClick(View v) {
          switch (v.getId()){
              case R.id.main_start:
                  boolean flag = bluetoothAdapter.enable();
                  if(!flag){
                      Intent intent = new Intent();
                      intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//启动蓝牙
                      intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//开启本设备可被发现
                      intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);//指定搜索时间,
                      startActivityForResult(intent,100);
                  }
                  break;
              case R.id.main_stop:
                  bluetoothAdapter.disable();//关闭蓝牙
                  list.clear();
                  adapter.refresh(list);
                  break;
              case R.id.main_serch:
                  bluetoothAdapter.startDiscovery();//开启搜索
                  break;
                  default:
                      break;
          }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100 ){

        }
    }

    private class BluetoothReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                   String action = intent.getAction();
                   switch (action){
                       case BluetoothDevice.ACTION_FOUND:
                           //搜索到一台蓝牙设备进入一次FOUND
                           //搜索到的设备保存到list中
                           BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                           Bean bean = new Bean();
                           bean.name = bluetoothDevice.getName();
                           bean.address = bluetoothDevice.getAddress();
                           bean.bluetoothDevice = bluetoothDevice;
                           Log.e("######",bluetoothDevice.getName());
                           list.add(bean);

                           adapter.refresh(list);
                           break;

                       case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:

                           adapter.refresh(list);
                           break;
                           default:
                               break;
                   }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值