Được tạo bởi Blogger.

Labels

Thứ Hai, 13 tháng 6, 2016

AndroidAdvanced - Bluetooth Example


Trong số rất nhiều cách, Bluetooth là một cách để gửi hoặc nhận dữ liệu giữa hai thiết bị khác nhau. Nền tảng Android có hỗ trợ cho khung truyền bluetooth, cho phép một thiết bị trao đổi dữ liệu không dây với thiết bị bluetooth khác.

Android cung cấp Bluetooth API cho nền tảng các thao tác khác nhau:
     + Quét các thiết bị Bluetooth khác
     + Nhận một danh sách các thiết bị đã ghép nối
     + Kết nối tới một thiết bị khác thông qua service discovery 

Android cung cấp class BluetoothAdapter để giao tiếp với Bluetooth. Tạo một đối tượng của nó bằng cách gọi phương thức tĩnh getDefaultAdapter(). Cú pháp của nó như dưới đây:


Để cho phép Bluetooth của thiết bị, gọi intent với hằng số Bluetooth ACTION_REQUEST_
ENABLE. Cú pháp của nó là:


Ngoài hằng số này, có các hằng số khác được cung cấp bởi API, hỗ trợ các tính năng khác. Chúng được liệt kê dưới đây:


Một khi bạn đã cho phép Bluetooth, bạn có thể nhận một danh sách các thiết bị đã kết nối bằng cách gọi phương thức getBondedDevices(). Nó trả về một tập các thiết bị Bluetooth. Cú pháp của nó là:


Ngoài các thiết bị đã ghép nối, có các phương thức khác trong API cho phép kiểm soát Bluetooth nhiều hơn. Chúng được liệt kê dưới đây.


Example
Ví dụ này sẽ cho thấy class BluetoothAdapter thao tác Bluetooth và hiển thị danh sách các thiết bị đã ghép nối bằng Bluetooth.

Để thử với ví dụ này, bạn cần chạy nó trong một thiết bị thực.

Bước 1: Bạn sẽ sử dụng Android Studio để tạo một Android application a package com.example. sairamkrishna.myapplication;. Trong khi tạo project này, phải đảm bảo rằng bạn Target SDK và biên dịch với phiên bản Android SDK mới nhất để sử dụng các mức API cao hơn.

Bước 2: Điều chỉnh file src/MainActivity.java để thêm code.

Bước 3: Điều chỉnh file layout XML res/layout/activity_main.xml để thêm bất kỳ thành phần GUI nào nếu được yêu cầu.

Bước 4: Điều chỉnh AndroidManifest.xml để thêm các giấy phép cần thiết.

Bước 5: Chạy ứng dụng và chọn một thiết bị android đang chạy và cài đặt ứng dụng trên nó và kiểm trả kết quả.

Đâ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 Set<BluetoothDevice>pairedDevices;
   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);
   }
}

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">
   
   <TextView android:text="Bluetooth Example" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Turn On"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_toStartOf="@+id/imageView"
      android:layout_toLeftOf="@+id/imageView"
      android:clickable="true"
      android:onClick="on" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Get visible"
      android:onClick="visible"
      android:id="@+id/button2"
      android:layout_alignBottom="@+id/button"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="List devices"
      android:onClick="list"
      android:id="@+id/button3"
      android:layout_below="@+id/imageView"
      android:layout_toRightOf="@+id/imageView"
      android:layout_toEndOf="@+id/imageView" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="turn off"
      android:onClick="off"
      android:id="@+id/button4"
      android:layout_below="@+id/button"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />
      
   <ListView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/listView"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/button"
      android:layout_alignStart="@+id/button"
      android:layout_below="@+id/textView2" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Paired devices:"
      android:id="@+id/textView2"
      android:textColor="#ff34ff06"
      android:textSize="25dp"
      android:layout_below="@+id/button4"
      android:layout_alignLeft="@+id/listView"
      android:layout_alignStart="@+id/listView" />

</RelativeLayout>

Đây là nội dung của String.xml

<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>

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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <uses-permission android:name="android.permission.BLUETOOTH"/>
   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

Hãy thử chạy ứng dụng của bạn. Tôi giả sử rằng bạn đã kết nối thiết bị Android thực với máy tính của bạn. Để chạy ứng dụng từ Android studio, mở một trong những file activity của ứng dụng và click Run  từ thanh công cụ. Trước khi bắt đầu ứng dụng của bạn, Android studio sẽ hiển thị cửa sổ dưới đây để chọn một lựa chọn nơi bạn muốn chạy ứng dụng Android của mình.


Bây giờ chọn Turn On để bật bluetooth. Nhưng như bạn chọn nó, Bluetooth của bạn sẽ không được bật. Trong thực tế, nó sẽ hỏi sự cấp phép của bạn để cho phép Bluetooth.




Bây giờ chỉ cần chọn nút Get Visible  để bật visibility của bạn. Màn hình dưới đây sẽ xuất hiện để yêu cầu sự cấp phép của bạn để được phát hiện trong 120 giây.


Bây giờ chỉ cần chọn lựa chọn List Devices. Nó sẽ liệt kê xuống dưới các thiết bị đã ghép nối trong list view. Trong trường hợp của tôi, tôi có duy nhất một thiết bị đã được ghép nối. Nó như dưới đây.


Bây giờ chỉ cần chọn nút Turn off để tắt Bluetooth. Đoạn tin dưới đây sẽ xuất hiện khi bạn tắt Bluetooth cho biết là đã tắt Bluetooth thành công.


END. THANKS FOR READ!

0 nhận xét:

Đăng nhận xét