Friday, 28 October 2011

Android Bluetooth sample app







This is a simple and powerful bluetooth app.Using this you can turn_on bluetooth,start discoverable with a simple touch,even turn_off your bluetooth.This will not work on emulator since bluetooth support is not added.

Java source code



package com.example.bluetooth;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
      private static final int REQUEST_ENABLE_BT = 0;
        private static final int REQUEST_DISCOVERABLE_BT = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    final TextView out=(TextView)findViewById(R.id.out);
    final Button button = (Button) findViewById(R.id.button1);
    final Button button1 = (Button) findViewById(R.id.button2);
    final Button button2 = (Button) findViewById(R.id.button3);
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
       out.append("device not supported");
    }
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    });
    button1.setOnClickListener(new View.OnClickListener() {
     @Override
        public void onClick(View arg0) {
            if (!mBluetoothAdapter.isDiscovering()) {
//                   out.append("MAKING YOUR DEVICE DISCOVERABLE");
                   Context context = getApplicationContext();
                   CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
                   int duration = Toast.LENGTH_SHORT;

                   Toast toast = Toast.makeText(context, text, duration);
                   toast.show();
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
                 
            }
        }
    });
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {  
            mBluetoothAdapter.disable();
//            out.append("TURN_OFF BLUETOOTH");
            Context context = getApplicationContext();
               CharSequence text = "TURNING_OFF BLUETOOTH";
               int duration = Toast.LENGTH_LONG;
               Toast toast = Toast.makeText(context, text, 15);
               toast.show();
            }
    });
}

}



Xml code



<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:background="@drawable/ic_launcher"
    tools:context=".MainActivity" >

<TextView android:text="" android:id="@+id/out" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="49dp"
        android:text="TURN_ON" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="27dp"
        android:text="DISCOVERABLE" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="28dp"
        android:text="TURN_OFF" />

</RelativeLayout>

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.bluetooth"
    android:versionCode="1"
    android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.bluetooth.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>





Download.apk file


http://www.4shared.com/zip/7OHBkCE_ce/Bluetooth.html




33 comments:

  1. Hi, I am getting the infamous "Application has stopped unexpectedly. Please try again." dialog when I run this code on my android device. And since the emulator does not support bluetooth there is no way to debug and find out where the code is crashing. I have the necessary permissions ie BLUETOOTH_ADMIN and BLUETOOTH. It would be great if you could help me out.

    ReplyDelete
  2. Please let me know on which android device ur using this code.

    ReplyDelete
    Replies
    1. in Manifest File:
      android:targetSdkVersion="16"

      set your target SDK according to it. :)

      Delete
  3. i ma also getting the same error

    ReplyDelete
  4. Leave ur mail id to support you. I ll try this code and post the .apk file today.

    ReplyDelete
  5. There are no errors in the above code. I have tested it on my phone(HTC desire V) . So please test only on any android device other than emulator. I have also uploaded .apk file for testing purpose. enjoy friends.

    ReplyDelete
  6. Thank you. It is very simple and easy one and I am able to run the application perfectly. But I want to have a program from you that will enable user to turn on bluetooth and chat with the other Android device over bluetooth.

    ReplyDelete
  7. I have got the error in getMenuInflater().inflate(R.menu.activity_main, menu);

    ReplyDelete
  8. I have got the error in this statement.....
    getMenuInflater().inflate(R.menu.activity_main, menu);

    ReplyDelete
  9. ANKUR. I hope your trying to create menu using method getMenuInflater(). When you press the menu button you will get this error.Because it will search for menu file. Which has to be located in /res/menu . You can implement in xml instead.

    Please refer to this example.(http://www.java2s.com/Code/Android/UI/GetMenutitle.htm).

    ReplyDelete
  10. Hello ANUKUR. Now i have removed the method getMenuInflater().
    Try the same code . It will work with out any error.

    ReplyDelete
  11. Hello Bhushan, I'm Krunal...I'm working on an android project.. I tried running this app but got the error...
    "Application has stopped unexpectedly"
    Thanks in advance...
    my id is krunal_717@yahoo.co.in

    ReplyDelete
  12. Thank you Bhushan......nice tutorial....it helped a lot...
    Thanks once again.....

    ReplyDelete
  13. hii......the code is ok......and its working.....plz dont try to run it on ur emulator....run in smartphones...it will work....thanku sir...thanks alot.......

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Hi its great Bhushan. I m new to android world. Please help me with a code that will automatically enable bluetooth n receive a string from another bluetooth device.. Thank u in advance...
    my id is rishiskeshav91@gmail.com.
    please help its urgent

    ReplyDelete
  16. hello sir i m T.Y.B.Sc.It student, i want to make the project on Android Bluetooth chat application....in this application those who is having the my app could communicate with each other through the msgs chat...what requirement for this app?

    ReplyDelete
  17. HELLO HUNK. First start with server and client connectivity. In chat service you will be using UUID . UUID is an immutable representation of a 128-bit universally unique identifier UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); . After that you should get the device list. Reference links
    1.(http://developer.android.com/reference/java/util/UUID.html).
    2.(http://developer.android.com/guide/topics/connectivity/bluetooth.html)

    ReplyDelete
  18. thank you bhushan sir, its nice to see these code. but i just wnat to use bluetooth connectivity to a mono bluetooth handfree to play media music on it. since there is no option to play music via bluetooth in default android music player like other as in nokia or other mobile OS. can i integrate this functionality to a media player? there is only one free app BTmono avail in play store to do this task. my Email id is jawedkhan0405@gmail.com. aiting for your reply

    ReplyDelete
  19. Hello Jawed. Please go through the below steps. This helps you to play audio using bluetooth.

    Audio over Bluetooth

    An accessory that connects with Android over Bluetooth can use an Advanced Audio Distribution Profile (A2DP) connection stream music for playback. Playing audio over a Bluetooth with A2DP is supported on Android 1.5 (API Level 3) and higher. An Android user can connect to an accessory that supports this profile using the system Settings > Bluetooth and play music directly to the accessory without the need for a secondary application.

    Note: If you want to provide a custom application for output to your audio accessory, note that the Android 3.0 (API Level 11) allows applications to operate an A2DP connection using the BluetoothA2dp class.
    Next steps

    To get started on building an audio accessory that uses a Bluetooth connection:
    Select a hardware platform or build an hardware device that can support Bluetooth communications and the A2DP connection profile.
    Review the ADK 2012 firmware source code (/adk2012/board/library/ADK2/), which includes an example implementation of an audio playback accessory using a Bluetooth connection.

    Note: The ADK 2012 source code includes an open source Bluetooth stack that is built for the Texas Instruments CC2564 chip, but can work with any Bluetooth chip that implements a standard Host/Controller Interface (HCI).

    ReplyDelete
  20. thanks for the source but how do i host a game through bluetooth for multiplayers

    ReplyDelete
  21. Hello Yevgeniy Goncharov. I have uploaded with a new link. Try downloading now.

    ReplyDelete
  22. i cantdownload from this link
    http://www.fileserve.com/file/kxpNkKM/Bluetooth.zip
    pls can you update any other file server ?

    ReplyDelete
  23. Hi can you tell me how to send the file using bluetooth.

    ReplyDelete
  24. Hello Aravinth. Using intent you can send a file through bluetooth. The basic idea is given below. Change the source path in the program.
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/jpg");
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f) );
    startActivity(intent);

    ReplyDelete
  25. Thanks Alot man.. because of you such people i continued my programming journey.. (y) salute (y)

    ReplyDelete
  26. Hei Bhushan,

    I wanted a interface between my phone app and my PC. Also I wan the data to be received via a bluetooth serial port in my PC. I'm just stuck. I have use used a RFcomm socket. I am not even sure will this protocol support serial. At times it says it has connected ... also i need to know if the socket is connected properly would i see the connected sign in phone around the bluetooth icon like this ><

    ReplyDelete
  27. Hi!
    Nice Tutorial Bro.
    Is there any way to discovered any Bluetooth device that are in range without triggered any button, touching device screen or scan button.
    I mean to say when my device Bluetooth is ON, automatically discovered new Bluetooth and send notification that xyz Bluetooth is in range. Even my android device is in my pocket.

    ReplyDelete
  28. Hello kishore kumar . I have uploaded the same file in 4shared.com. Now you can download it

    ReplyDelete
  29. where i get the BLUETOOTH CHAT source code rar file,which canbe compatible for Importing in Ecllipse Application.

    ReplyDelete