Bluetooth trong Android



Bluetooth là một cách để truyền và nhận dữ liệu giữa hai thiết bị khác nhau. Android platform cung cấp hỗ trợ cho Bluetooth framework cho phép một thiết bị trao đổi dữ liệu với thiết bị Bluetooth khác.

Android cung cấp Bluetooth API để thực hiện các hoạt động:

  • Quét các thiết bị Bluetooth khác.

  • Lấy một danh sách các thiết bị có thể ghép cặp (Paired Device).

  • Kết nối với thiết bị khác thông qua dịch vụ dò tìm.

Android cung cấp lớp BluetoothAdapter để giao tiếp với Bluetooth. Tạo một đối tượng của lớp này bởi gọi phương thức static là getDefaultAdapter(). Cú pháp như sau:

private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();

Để kích hoạt Bluetooth của thiết bị, gọi Intent với hằng ACTION_REQUEST_ENABLE. Cú pháp như sau:

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);       

Ngoài hằng này, API còn cung cấp một số hằng khác để hỗ trợ các tác vụ khác nhau. Bảng dưới liệt kê các hằng này:

Stt Constant & Miêu tả
1 ACTION_REQUEST_DISCOVERABLE

Hằng này được sử dụng để bật trình dò tìm của Bluetooth

2 ACTION_STATE_CHANGED

Hằng này thông báo rằng trạng thái Bluetooth đã bị thay đổi

3 ACTION_FOUND

Hằng này được sử dụng để nhận thông tin về mỗi thiết bị đã được dò tìm

Khi bạn kích hoạt Bluetooth, bạn có thể lấy một danh sách các thiết bị có thể ghép cặp bằng cách gọi phương thức getBondedDevices(). Nó trả về một tập hợp các thiết bị Bluetooth. Cú pháp là:

private SetpairedDevices;
pairedDevices = BA.getBondedDevices();

Ngoài các thiết bị có thể ghép đôi, API còn cung cấp một số phương thức khác để giúp bạn có nhiều điều khiển hơn thông qua Bluetooth.

Stt Phương thức & Miêu tả
1 enable()

Phương thức này kích hoạt Adapter nếu nó chưa được kích hoạt

2 isEnabled()

Phương thức này trả về true nếu Adapter đã được kích hoạt

3 disable()

Phương thức này vô hiệu hóa Adapter

4 getName()

Phương thức này trả về tên của Bluetooth Adapter

5 setName(String name)

Phương thức này thay đổi tên của Bluetooth

6 getState()

Phương thức này trả về trạng thái hiện tại của Bluetooth Adapter

7 startDiscovery()

Phương thức này bắt đầu tiến trình dò tìm của Bluetooth trong 120 s

Ví dụ sau minh họa lớp BluetoothAdapter để thao tác Bluetooth và liệt kê các thiết bị có thể ghép đôi.

Để thử nghiệm ví dụ, bạn cần chạy trên một thiết bị thực sự.

Sau đây là nội dung của src/MainActivity.java

package com.example.sairamkrishna.myapplication;import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;import java.util.ArrayList;
import java.util.List;
import java.util.Set;public class MainActivity extends Activity  {
   Button b1,b2,b3,b4;
   private BluetoothAdapter BA;
   private SetpairedDevices;
   ListView lv;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      b1 = (Button) findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);
      b3=(Button)findViewById(R.id.button3);
      b4=(Button)findViewById(R.id.button4);
      
      BA = BluetoothAdapter.getDefaultAdapter();
      lv = (ListView)findViewById(R.id.listView);
   }
   
   public void on(View v){
      if (!BA.isEnabled()) {
         Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(turnOn, 0);
         Toast.makeText(getApplicationContext(),"Turned on",Toast.LENGTH_LONG).show();
      }
      else
      {
         Toast.makeText(getApplicationContext(),"Already on", Toast.LENGTH_LONG).show();
      }
   }
   
   public void off(View v){
      BA.disable();
      Toast.makeText(getApplicationContext(),"Turned off" ,Toast.LENGTH_LONG).show();
   }
   
   public  void visible(View v){
      Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
      startActivityForResult(getVisible, 0);
   }
   
   public void list(View v){
      pairedDevices = BA.getBondedDevices();
      ArrayList list = new ArrayList();
      
      for(BluetoothDevice bt : pairedDevices)
      list.add(bt.getName());
      Toast.makeText(getApplicationContext(),"Showing Paired Devices",Toast.LENGTH_SHORT).show();
      
      final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
      lv.setAdapter(adapter);
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

Sau đây là nội dung của activity_main.xml


   
   
      
   
      
   
      
   

Sau đây là nội dung của Strings.xml


   My Application
   Hello world!
   Settings

Sau đây là nội dung của AndroidManifest.xml



   
   
   
   
      
      
         
         
            
            
         
         
      
      
   

Cuối cùng, bạn chạy ứng dụng Android vừa tạo ở trên.

Bluetooth trong Android

Bây giờ, chọn nút Turn On để bật Bluetooth. Nhưng khi bạn chọn nó, thì thì Bluetooth sẽ không được bật lên ngay, nó sẽ hỏi bạn về permission để kích hoạt Bluetooth.

Bluetooth trong Android

Bây giờ chọn nút GET VISIBLE để bật tính năng Visibility. Màn hình sau xuất hiện hỏi bạn về permission để bật dò tìm trong 120 s.

Bluetooth trong Android

Chọn tùy chọn List Devices. Nó sẽ liệt kê các thiết bị có thể ghép đôi.

Bluetooth trong Android

Chọn nút TURN OFF để tắt Bluetooth. Thông báo sau sẽ xuất hiện:

Bluetooth trong Android