iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 18
0

前言

現今 Android 系統的手機藍芽已經幾乎成為了基本配置,所以今天本篇就是要說如何搜尋到你附近的藍芽

操作

第一步:添加需要使用的套件到build.dradle

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

第二步:設定布局文件樣式

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/statusBluetoothTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAlignment="center"
        android:textColor="#000"
        android:textSize="25dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />
    <Button
        android:id="@+id/onButn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="148dp"
        android:minWidth="200dp"
        android:text="打開藍芽"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.436"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/offButn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp"
        android:minWidth="200dp"
        android:text="關閉藍芽"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.473"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/onButn" />
    <Button
        android:id="@+id/discoverableBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp"
        android:minWidth="200dp"
        android:text="使藍芽可被偵測"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/offButn" />
    <Button
        android:id="@+id/PairedBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:minWidth="200dp"
        android:text="得到設備"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.473"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/discoverableBtn" />
    <TextView
        android:id="@+id/pairTv"
        android:layout_width="403dp"
        android:layout_height="15dp"
        android:layout_marginTop="44dp"
        android:minWidth="200dp"
        android:text=""
        android:textColor="#000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/PairedBtn" />
</androidx.constraintlayout.widget.ConstraintLayout>

第三步:得到藍芽的 Adapter 並連接元件

    private static final int REQUEST_ENABLE_BT = 0;
    private static final int REQUEST_DISCOVER_BT = 1;
    private TextView  mPairedTv;
    Button mOnBtn, mOffBtn, mDiscoverBtn, mPairedBtn;
    BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPairedTv = findViewById(R.id.pairTv);
        mOnBtn = findViewById(R.id.onButn);
        mOffBtn = findViewById(R.id.offButn);
        mDiscoverBtn = findViewById(R.id.discoverableBtn);
        mPairedBtn = findViewById(R.id.PairedBtn);

第四步:判斷是否支援藍芽以及藍芽是否開啟

if (bluetoothAdapter == null) {
            showToast("Bluetooth is not available");
        } else {
            showToast("Bluetooth is  available");
            if (bluetoothAdapter.isEnabled()) {
                showToast("藍芽還未開啟");
            } else {
                showToast("藍芽已開啟");

            }
            ```
第五步:製作開啟藍芽的程式

private void onbtn() {
if (!bluetoothAdapter.isEnabled()) {
showToast("Turning on Bluetooth..");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
} else {
showToast("Bluetooth is already on");
}

}
    ```

第六步:製作關閉藍芽的程式

private void offButn() {
        if (bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.disable();
            showToast("Turning  Bluetooth off");
        } else {
            showToast("Bluetooth is already off");
        }

    }
    ```
第七步:使藍芽可以被偵測

private void discoverableBtn() {
if (!bluetoothAdapter.isDiscovering()) {
showToast("Making Your Device Discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_DISCOVER_BT);
}

}
第八步:列出偵測到的程式

private void PairedBtn() {
if (bluetoothAdapter.isEnabled()) {
mPairedTv.setText("Paired Devices");
Set devices = bluetoothAdapter.getBondedDevices();

    for (BluetoothDevice device : devices) {
        mPairedTv.append("\n Device : " + device.getName() + " , " + device);
    }
} else {
    showToast("Turn On bluetooth to get paired devices");
}
}

完整程式碼▼▼▼

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVER_BT = 1;
private TextView  mPairedTv;
Button mOnBtn, mOffBtn, mDiscoverBtn, mPairedBtn;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mPairedTv = findViewById(R.id.pairTv);
    mOnBtn = findViewById(R.id.onButn);
    mOffBtn = findViewById(R.id.offButn);
    mDiscoverBtn = findViewById(R.id.discoverableBtn);
    mPairedBtn = findViewById(R.id.PairedBtn);
    mPairedBtn.setOnClickListener(this);
    mOnBtn.setOnClickListener(this);
    mOffBtn.setOnClickListener(this);
    mDiscoverBtn.setOnClickListener(this);
    if (bluetoothAdapter == null) {
        showToast("Bluetooth is not available");
    } else {
        showToast("Bluetooth is  available");
        if (bluetoothAdapter.isEnabled()) {
            showToast("藍芽還未開啟");
        } else {
            showToast("藍芽已開啟");
        }
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    switch (requestCode) {
        case REQUEST_ENABLE_BT:
            if (resultCode == RESULT_OK) {
                showToast("Bluetooth is On");
            } else {
                showToast("Bluetooth is Off");
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

private void showToast(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.onButn:
            onbtn();
            break;
        case R.id.offButn:
            offButn();
            break;
        case R.id.discoverableBtn:
            discoverableBtn();
            break;
        case R.id.PairedBtn:
            PairedBtn();
            break;
    }
}
private void onbtn() {
    if (!bluetoothAdapter.isEnabled()) {
        showToast("Turning on Bluetooth..");
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, REQUEST_ENABLE_BT);
    } else {
        showToast("Bluetooth is already on");
    }

}
private void offButn() {
    if (bluetoothAdapter.isEnabled()) {
        bluetoothAdapter.disable();
        showToast("Turning  Bluetooth off");
    } else {
        showToast("Bluetooth is already off");
    }

}
private void discoverableBtn() {
    if (!bluetoothAdapter.isDiscovering()) {
        showToast("Making Your Device Discoverable");
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        startActivityForResult(intent, REQUEST_DISCOVER_BT);
    }

}
private void PairedBtn() {
    if (bluetoothAdapter.isEnabled()) {
    mPairedTv.setText("Paired Devices");
    Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();

    for (BluetoothDevice device : devices) {
        mPairedTv.append("\n Device : " + device.getName() + " , " + device);
    }
} else {
    showToast("Turn On bluetooth to get paired devices");
}
}

}


上一篇
第17篇:音量鍵控制
下一篇
第19篇:RecyclerView
系列文
Android的30天學習歷程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言