網頁

2022年2月13日 星期日

Android Studio - Bluetooth 掃描設備程式(三十九)

Android Studio - Bluetooth 掃描設備程式(三十九):

當設定 Bluetooth 許可權限完成後,便可以開始編寫程式,首先是要設定手機藍牙,然後啟動手機藍牙,再掃描周邊的藍牙設備,顯示藍牙設備資料。

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

Bluetooth 掃描設備程式編程步驟:
  • 設定 Bluetooth 許可權限後
  • 設定手機藍牙
  • 啟動手機藍牙
  • 掃描周邊的藍牙設備
  • 顯示周邊藍牙設備資料
MainActivity.java:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

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;

 

public class MainActivity extends AppCompatActivity {

 

    // GUI Components

    private TextView mtv_status;

    private Button mbtn_on;

    private Button mbtn_Scan;

    private ListView mlv_device;

 

    private BluetoothAdapter mBTAdapter;

    private ArrayAdapter<String> mBTArrayAdapter;

 

    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);

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

 

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

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

 

        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();

            }

        });

    }

 

    // Bluetooth Turn ON

    private void bluetoothOn(){

        if (!mBTAdapter.isEnabled()) {

            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

            //mBluetoothStatus.setText("Bluetooth Enabled");

            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

        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));

            }

            else{

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

            }

        }

    }

 

    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);

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

                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="12dp"

        android:layout_marginLeft="12dp"

        android:layout_marginTop="11dp"

        android:text="Scan" />

 

    <ListView

        android:id="@+id/lv_device"

        android:layout_width="384dp"

        android:layout_height="548dp"

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

</RelativeLayout>


Android Studio Bluetooth 掃描設備程式

2022年 2月 13日(Sun)天氣報告
氣溫:33.0°F / 1.0°C @ 07:00
風速:每小時 5公里
降雨機會:2%
相對濕度:百分之 82%
天氣:大致晴朗

沒有留言:

張貼留言