2022年2月14日 星期一

Android Studio - Bluetooth 綁定設備程式(四十)

Android Studio - Bluetooth 綁定設備程式(四十):

當設定 Bluetooth 許可權限完成後,便可以開始編寫程式,首先是要設定手機藍牙,然後啟動手機藍牙,再掃描周邊的藍牙設備,顯示藍牙設備資料,選擇藍牙設備作綁定配對(Pair)。因為沒有其它這次綁定 Bluetooth(藍牙)設備,設備是一台舊 Huawei G7-TL00 手機,綁定配對(Pair)都成功。

Android Studio Bluetooth 綁定設備程式
操作系統:Windows 7 64-bit 版本
開發環境:Android Studio 4.0.1 版本
原程式:C:\Development\Development_Android\Android_Project\DIY-Android-010-01B Bluetooth Pair
程式:C:\Development\Development_Android\Android_Project\DIY-Android-010-01B Bluetooth Pair

Bluetooth 掃描設備程式編程步驟:
設定 Bluetooth 許可權限後
設定手機藍牙
啟動手機藍牙
掃描周邊的藍牙設備
顯示周邊藍牙設備資料
選擇藍牙設備作綁定配對

MainActivity.java:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.Toast;

import android.content.Intent;

import android.content.Context;

import android.content.IntentFilter;

import android.view.View;

 

// Bluetooth API

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;

import android.content.BroadcastReceiver;

 

import java.lang.reflect.Method;

import java.util.ArrayList;

 

public class MainActivity extends AppCompatActivity {

 

    // GUI Components

    private TextView mtv_status;

    private Button mbtn_on;

    private Button mbtn_Scan;

    private Button mbtn_Pair;

    private Button mbtn_UnPair;

    private ListView mlv_device;

    private int mlvPosition;

 

    private BluetoothAdapter mBTAdapter;

    private ArrayAdapter<String> mBTArrayAdapter;

 

    private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();

 

    private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        mbtn_on = (Button) findViewById(R.id.btn_on);

        mbtn_Scan = (Button) findViewById(R.id.btn_scan);

        mbtn_Pair = (Button) findViewById(R.id.btn_pair);

        mbtn_UnPair=(Button) findViewById(R.id.btn_unpair);

 

        mBTArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

        mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio

        mlv_device = (ListView)findViewById(R.id.lv_device);

        mlv_device.setAdapter(mBTArrayAdapter); // assign model to view

 

        mbtn_on.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                bluetoothOn();

            }

        });

 

        mbtn_Scan.setOnClickListener(new View.OnClickListener(){

            @Override

            public void onClick(View v){

                scan();

            }

        });

 

        mbtn_Pair.setOnClickListener(new View.OnClickListener(){

            @Override

            public void onClick(View v){

                BluetoothDevice device = mDeviceList.get(mlvPosition);

                Toast.makeText(getApplicationContext(),"Pair " + mlvPosition, Toast.LENGTH_SHORT).show();

                pairDevice(device);

            }

        });

 

        mbtn_UnPair.setOnClickListener(new View.OnClickListener(){

            @Override

            public void onClick(View v){

                BluetoothDevice device = mDeviceList.get(mlvPosition);

                Toast.makeText(getApplicationContext(),"UnPair " + mlvPosition, Toast.LENGTH_SHORT).show();

                unpairDevice(device);

            }

        });

 

        // ListView

        mlv_device.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                ListView listView = (ListView) parent;

                mlvPosition = position;

                Toast.makeText(getApplicationContext(),"Select " + text3, Toast.LENGTH_SHORT).show();

            }

        });

    }

 

    // Bluetooth Turn ON

    private void bluetoothOn(){

        if (!mBTAdapter.isEnabled()) {

            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

            Toast.makeText(getApplicationContext(),"Bluetooth Turned On",Toast.LENGTH_SHORT).show();

        }

        else{

            Toast.makeText(getApplicationContext(),"Bluetooth is Already On", Toast.LENGTH_SHORT).show();

        }

    }

 

    // Discovery Bluetooth Device

    private void scan(){

        // Check if the device is already discovering

        mlvPosition = -1;

        mBTArrayAdapter.clear();

        mDeviceList.clear();

 

        if(mBTAdapter.isDiscovering()){

            mBTAdapter.cancelDiscovery();

            Toast.makeText(getApplicationContext(),"Scan Stopped",Toast.LENGTH_SHORT).show();

        }

        else{

            if(mBTAdapter.isEnabled()) {

                mBTArrayAdapter.clear(); // clear items

                mBTAdapter.startDiscovery();

                Toast.makeText(getApplicationContext(), "Discovery Started", Toast.LENGTH_SHORT).show();

                registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));

                registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));

            }

            else{

                Toast.makeText(getApplicationContext(), "Bluetooth Not On", Toast.LENGTH_SHORT).show();

            }

        }

    }

 

    private void pairDevice(BluetoothDevice device) {

        try {

            Method method = device.getClass().getMethod("createBond", (Class[]) null);

            method.invoke(device, (Object[]) null);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

    private void unpairDevice(BluetoothDevice device) {

        try {

            Method method = device.getClass().getMethod("removeBond", (Class[]) null);

            method.invoke(device, (Object[]) null);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

    final BroadcastReceiver blReceiver = new BroadcastReceiver() {

        @Override

        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

 

            if(BluetoothDevice.ACTION_FOUND.equals(action)){

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                mDeviceList.add(device);

                mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());

                mBTArrayAdapter.notifyDataSetChanged();

            }

        }

    };

 

    private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {

                final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);

                final int prevState       = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);

                if (state == BluetoothDevice.BOND_BONDED&&prevState == BluetoothDevice.BOND_BONDING) {

                    Toast.makeText(getApplicationContext(), "Pair", Toast.LENGTH_SHORT).show();

                } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){

                    Toast.makeText(getApplicationContext(), "UnPair", Toast.LENGTH_SHORT).show();

                }

                mBTArrayAdapter.notifyDataSetChanged();

            }

        }

    };

}


activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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"

tools:context=".MainActivity">

 

<TextView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_alignParentStart="true"

    android:layout_alignParentLeft="true"

    android:layout_alignParentTop="true"

    android:layout_marginStart="132dp"

    android:layout_marginLeft="132dp"

    android:layout_marginTop="16dp"

    android:text="Hello Bluetooth!" />

 

<Button

    android:id="@+id/btn_on"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_alignParentStart="true"

    android:layout_alignParentLeft="true"

    android:layout_alignParentTop="true"

    android:layout_marginStart="12dp"

    android:layout_marginLeft="12dp"

    android:layout_marginTop="40dp"

    android:text="ON" />

 

<Button

    android:id="@+id/btn_scan"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_below="@+id/btn_on"

    android:layout_alignParentStart="true"

    android:layout_alignParentLeft="true"

    android:layout_marginStart="10dp"

    android:layout_marginLeft="12dp"

    android:layout_marginTop="11dp"

    android:text="Scan" />

 

    <ListView

        android:id="@+id/lv_device"

        android:layout_width="366dp"

        android:layout_height="333dp"

        android:layout_below="@+id/btn_scan"

        android:layout_alignParentBottom="true"

        android:layout_centerHorizontal="true"

        android:layout_marginStart="16dp"

        android:layout_marginLeft="16dp"

        android:layout_marginTop="5dp"

        android:layout_marginBottom="246dp" />

 

    <Button

        android:id="@+id/btn_pair"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_alignParentEnd="true"

        android:layout_alignParentRight="true"

        android:layout_marginTop="40dp"

        android:layout_marginEnd="15dp"

        android:layout_marginRight="15dp"

        android:text="Pair" />

 

    <Button

        android:id="@+id/btn_unpair"

        android:layout_width="96dp"

        android:layout_height="wrap_content"

        android:layout_below="@+id/btn_pair"

        android:layout_alignParentEnd="true"

        android:layout_alignParentRight="true"

        android:layout_marginTop="10dp"

        android:layout_marginEnd="13dp"

        android:layout_marginRight="13dp"

        android:text="UnPair" />

 

</RelativeLayout>


Android Studio Bluetooth 綁定設備程式
2022年 2月 14日(Mon)天氣報告
氣溫:44.0°F / 7.0°C @ 07:00
風速:每小時 14公里
降雨機會:69%
相對濕度:百分之 88%
天氣:小陣雨
※ Happy Valentine's Day! 情人節快樂!

沒有留言:

張貼留言