Showing posts with label bluetooth. Show all posts
Showing posts with label bluetooth. Show all posts

Monday, 14 April 2014

Buetooth

Bluetooth:

      Bluetooth connectivity is a common way to share data from one device to another.Normally Bluetooth is used to share Media files like mp3 songs images or videos or files. 

Bluetooth Device Class:

       Bluetooth class, which describes general characteristics and capabilities of a device. For example, Generally when we connect to a Bluetooth Device like Computer, Laptop, Bluetooth Headset and Bluetooth other peripherals.And the Bluetooth class will specify the general device type such as a phone, a computer, or headset, and whether it's capable of services such as audio or telephony.

And today I am adding an other basic tutorial to get List of Paired Bluetooth Devices and get the Major Class (Headset, Computer or other Peripheral) of the Paired Bluetooth Devices:

OutPut:
onlaunchCheckbluetoothafter enabling bluetooth

paired devices list
Create new Android Project
Project Name: BlueToothPairing
//tested from 2.3.3 to current android sdk 
Build Target: Android 2.3.3   //or greater than that
Application Name: BlueToothPairing
Package Name: com.shaikhhamadali.blogspot.bluetoothpairing
Create Layout file: activity_pair

1. code of Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/Main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >
<TextView 
    android:id="@+id/tVBluetoothState" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<Button
    android:id="@+id/btnListPairedDevices" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="List Paired Devices" 
    android:enabled="false"
    /> 
</LinearLayout>


2. code of activityies:

   PairingActivity:

package com.shaikhhamadali.blogspot.bluetoothpairing;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PairingActivity extends Activity {
 //Create variables
 private static final int REQUEST_ENABLE_BT = 1;
 private static final int REQUEST_PAIRED_DEVICE = 2;

 //declare views/controls
 Button btnListPairedDevices;
 TextView tVBluetoothState;

 //declare Bluetooth Adapter
 BluetoothAdapter btAdapter;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_pair);
  //get reference of the UI Controls
  btnListPairedDevices = (Button)findViewById(R.id.btnListPairedDevices);
  tVBluetoothState = (TextView)findViewById(R.id.tVBluetoothState);
  //Get Default bluetooth adapter
  btAdapter = BluetoothAdapter.getDefaultAdapter();
  //Check the state of bluetooth
  CheckBlueToothState();
  //set listner for the button.
  btnListPairedDevices.setOnClickListener(btnListPairedDevicesOnClickListener);
 }

 private void CheckBlueToothState(){
  //does device support Bluetooth 
  if (btAdapter == null){
   tVBluetoothState.setText("Bluetooth NOT support");
  }else{
   //is Bluetooth enable
   if (btAdapter.isEnabled()){
    //is in discovery mode
    if(btAdapter.isDiscovering()){
     tVBluetoothState.setText("Bluetooth is currently in device discovery process.");
    }else{
     tVBluetoothState.setText("Bluetooth is Enabled.");
     btnListPairedDevices.setEnabled(true);
    }
   }else{
    tVBluetoothState.setText("Bluetooth is NOT Enabled!");
    //Enable Bluetooth by intent 
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
   }
  }
 }

 private Button.OnClickListener btnListPairedDevicesOnClickListener= new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // Create instance of intent
   Intent intent = new Intent();
   //set class for intent 
   intent.setClass(PairingActivity.this, ListPairedDevicesActivity.class);
   //and start list activity for result
   startActivityForResult(intent, REQUEST_PAIRED_DEVICE); 
  }};

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // is the request code for enable bluetooth or the paired devices
   if(requestCode == REQUEST_ENABLE_BT){
    //check Bluetooth state
    CheckBlueToothState();
   }
   if (requestCode == REQUEST_PAIRED_DEVICE){
    //do nothing is result is ok
    if(resultCode == RESULT_OK){
    }
   } 
  }   
}

   ListPairedDevicesActivity:

package com.shaikhhamadali.blogspot.bluetoothpairing;

import java.util.Set;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class ListPairedDevicesActivity extends ListActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  //Create ArrayAdapter to store the list of paired Bluetooth Devices
  ArrayAdapter<String> btArrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
  //Create instance of Bluetooth Adapter
  BluetoothAdapter bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
  //create Set instance to get the set of Paired devices  
  Set<BluetoothDevice> pairedDevices= bluetoothAdapter.getBondedDevices();
  //check that device has paired devices list or not
  if (pairedDevices.size() > 0) {
   //loop through the every paired device.
   for (BluetoothDevice device : pairedDevices) {
    //Get Name of the paired Device   
    String deviceBTName = device.getName();
    //Get Class of the Paired Device
    String deviceBTMajorClass= getBTMajorDeviceClass(device.getBluetoothClass().getMajorDeviceClass());
    //Add name and class of the Paired device
    btArrayAdapter.add(deviceBTName + "\n" + deviceBTMajorClass);
   }
  }
  //Set list Adapter to the ListActivity
  setListAdapter(btArrayAdapter);

 }

 private String getBTMajorDeviceClass(int major){
  //Types of the Bluetooth Classes
  switch(major){ 
  case BluetoothClass.Device.Major.AUDIO_VIDEO:
   return "AUDIO_VIDEO";
  case BluetoothClass.Device.Major.COMPUTER:
   return "COMPUTER";
  case BluetoothClass.Device.Major.HEALTH:
   return "HEALTH";
  case BluetoothClass.Device.Major.IMAGING:
   return "IMAGING"; 
  case BluetoothClass.Device.Major.MISC:
   return "MISC";
  case BluetoothClass.Device.Major.NETWORKING:
   return "NETWORKING"; 
  case BluetoothClass.Device.Major.PERIPHERAL:
   return "PERIPHERAL";
  case BluetoothClass.Device.Major.PHONE:
   return "PHONE";
  case BluetoothClass.Device.Major.TOY:
   return "TOY";
  case BluetoothClass.Device.Major.UNCATEGORIZED:
   return "UNCATEGORIZED";
  case BluetoothClass.Device.Major.WEARABLE:
   return "AUDIO_VIDEO";
  default: return "unknown!";
  }
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  super.onListItemClick(l, v, position, id);
  //set Result OK and finish the list activity
  Intent intent = new Intent();
  setResult(RESULT_OK, intent);
  finish();
 }

}

3. note that:

  • Good practice is to always check that is bluetooth supported, is Bluetooth ON or not, and is it in discovering mode.
  • As you can see above I have used some common class types that are supported by Bluetooth are listed here on developer.android.com.
  • You can connect to any device after getting list of all paired devices.
  • Learn more about BluetoothEnable Disable Bluetooth.

4. conclusion:

  • Some information about how to get Bluetooth paired devices list.
  • know how to get Class type of Bluetooth paired devices.
  • Know how to Create List Activity.
  • How to generate list of dynamic items.

    5. About the post:

    • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
    •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
    •  Hope you enjoy it!
        6. Source Code:
                you can download the source code from: GoogleDriveGithub

        Cheers,
        Hamad Ali Shaikh

        Friday, 20 September 2013


        1.What is Blue Tooth?

        Bluetooth is a wireless technology standard for exchanging data over short distances from fixed and mobile devices, creating personal area networks with high levels of security.

        Or

        Bluetooth is a way to exchange data with other devices without any wired connection.


        2.What Android Provides?


        Bluetooth API to perform several tasks such as:
        1. Scan for other Bluetooth devices (including Bluetooth Low Energy devices)
        2. Query the local Bluetooth adapter for paired Bluetooth devices
        3. Establish RFCOMM channels/sockets
        4. Connect to specified sockets on other devices
        5. Transfer data to and from other devices
        6. Manage multiple connections


        3.What Android BlueTooth API Provides?

        The android.bluetooth package provides a lot of interfaces classes to work with bluetooth such as:


        1. BluetoothAdapter
        2. BluetoothDevice
        3. BluetoothAssignedNumbers
        4. BluetoothServerSocket
        5. BluetoothSocket
        6. BluetoothProfile
        7. BluetoothClass
        8. BluetoothHeadset
        9. BluetoothProfile.ServiceListener
        10. BluetoothA2dp
        11. BluetoothHealth
        12. BluetoothHealthCallback
        13. BluetoothHealthAppConfiguration

        4.About BlueTooth Adapter Class?

        BluetoothAdapter  Represents the local device Bluetooth adapter. 
        BluetoothAdapter class can be used to perform fundamental tasks such as query a list of paired (bonded) devices, create a BluetoothServerSocket instance to listen for connection requests, initiate device discovery etc.

        5.What are the Constants of Bluetooth Adapter Class?

        BluetoothAdapter class provides many constants. Some of them are as follows:

        1. String ACTION_REQUEST_DISCOVERABLE
        2. String ACTION_REQUEST_ENABLE
        3. String ACTION_DISCOVERY_STARTED
        4. String ACTION_DISCOVERY_FINISHED
        5. String ACTION_STATE_CHANGED

        6.What are the Methods of Bluetooth Adapter Class?

        BluetoothAdapter class provides many Methods. Some of them commonly used are as follows:
        1. boolean setName(String name):      changes the bluetooth name.
        2. boolean enable():      enables the bluetooth adapter if it is disabled.
        3. static synchronized BluetoothAdapter getDefaultAdapter():      returns the instance of BluetoothAdapter.
        4. boolean isEnabled():      returns true if the bluetooth adapter is enabled.
        5. boolean disable():      disables the bluetooth adapter if it is enabled.
        6. String getName():      returns the name of the bluetooth adapter.
        7. int getState():      returns the current state of the local bluetooth adapter.
        8. Set getBondedDevices():      returns a set of paired (bonded) BluetoothDevice objects.
        9. boolean startDiscovery():      starts the discovery process.

        Thursday, 19 September 2013

        On Launch

        Enable/Disable BlueTooth

        on BlueTooth Enable

        Enable/Disable BlueTooth

        on BlueTooth Disable

        Enable/Disable BlueTooth


        Create new Android Project
        Project Name: System Settings
        //tested from 2.3.3 to current android sdk 
        Build Target: Android 2.3.3   //or greater than that
        Application Name: SystemSettings
        Package Name: com.shaikhhamadali.blogspot.systemsettings
        Create layout file: activity_Blue_tooth

          1. create layout:

        <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"
            >
        
            <TextView
                android:id="@+id/TVBlueTooth"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="90dp"
                android:text="Blue Tooth: Disable"
                android:textColor="#1BD6E0"
                android:textSize="40sp" />
        
            <ToggleButton
                android:id="@+id/tBBlueTooth"
                android:layout_width="300dp"
                android:layout_height="150dp"
                android:layout_centerInParent="true"
                android:textSize="30sp"
                android:textOff="Enable"
                android:textOn="Disable" />
        
        </RelativeLayout>
        
        • Add Permission in Manifest:
        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
        

        2. code of activity:


        package com.shaikhhamadali.blogspot.systemsettings;
        
        import android.app.Activity;
        import android.bluetooth.BluetoothAdapter;
        import android.os.Bundle;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.TextView;
        import android.widget.ToggleButton;
        
        public class BlueTooth_Toggle extends Activity{
         // constants
         static final String STATUS_ON = "Blue Tooth: Enable";
         static final String STATUS_OFF = "Blue Tooth: Disable";
        
         static final String TURN_ON = "Enable";
         static final String TURN_OFF = "Disable";
        
         // controls
         TextView TVBlueTooth;
         ToggleButton tBBlueTooth;
        
         //variable
         BluetoothAdapter mBluetoothAdapter; 
         @Override
         public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_blue_tooth);
        
          // load controls
          TVBlueTooth=(TextView)findViewById(R.id.TVBlueTooth);
          tBBlueTooth=(ToggleButton)findViewById(R.id.tBBlueTooth);
        
          // set click event for button
          tBBlueTooth.setOnClickListener(new OnClickListener() {
        
           @Override
           public void onClick(View v) {
            // TODO Auto-generated method stub
            // check current state first
            boolean state = isBlueToothEnable();
            // toggle the state
            if(state)toggleBlueTooth(false);
            else toggleBlueTooth(true);
            // update UI to new state
            updateUI(!state);  
        
           }
          });
         }
         public void updateUI(boolean state) {
          //set text according to state
          if(!state) {
           TVBlueTooth.setText(STATUS_OFF);
           tBBlueTooth.setText(TURN_ON);           
          } else {
           TVBlueTooth.setText(STATUS_ON);
           tBBlueTooth.setText(TURN_OFF);  
        
          }
         }
         public boolean isBlueToothEnable() {
          //get status of blue tooth
          mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
          return  mBluetoothAdapter.isEnabled();
         }
        
         public void toggleBlueTooth(boolean stat){
        
          mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
          if (stat) {
           mBluetoothAdapter.enable(); 
          } 
          else{
           mBluetoothAdapter.disable();
          }
         }
        }
        

        3. note that:
        • you can use this on button onclick,on action_down,on the fly etc.
        4. conclusion:
        • Some information about how to toggle BlueTooth (Enable /Disable).
        • Know how to update UI after toggle.
        • know what is BlueTooth Adapter.


        5. About the post:

        • The code seems to explain itself due to comments, if you have any question you can ask too!
        • Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
        •  Hope you enjoy it!

        6. Source Code:
                you can download the source code here

        Cheers,

        Hamad Ali Shaikh