Saturday, October 5, 2019

Android Bluetooth Device Discoverable with Examples

In android, Bluetooth is a communication network protocol, which allow a devices to connect wirelessly to exchange the data with other Bluetooth devices.

Generally, in android applications by using Bluetooth API’s we can implement Bluetooth functionalities, such as enable or disable a Bluetooth, searching for available Bluetooth devices, connecting with the devices and managing the data transfer between devices within the range.

In android, we can perform Bluetooth related activities by using BluetoothAdapter class in our applications. To know more about BluetoothAdapter, check this Android Bluetooth with Examples.

Android Bluetooth Enable Discoverability

To make the device discoverable to other devices, we need to start the new activity by calling startActivityForResult(intent, int) with the ACTION_REQUEST_DISCOVERABLE intent.

Following is the code snippet to enable the system’s discoverable mode to make sure that the device discoverable to other devices.

Intent dIntent =  new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.
EXTRA_DISCOVERABLE_DURATION300);
startActivity(dIntent);
If you observe above code snippet, we are making sure our device discoverable to other devices using ACTION_REQUEST_DISCOVERABLE. By default, the device becomes discoverable for 120 seconds. We can extend the device discoverable duration up to 3600 seconds (1 hour), by adding the EXTRA_DISCOVERABLE_DURATION extra.

As we discussed in previous tutorial Android Bluetooth with Examples, we need to set Bluetooth permissions in our android manifest file like show below to use Bluetooth features in our android applications.

<manifest ... >
<
uses-permission android:name="android.permission.BLUETOOTH"/>
<
uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<
uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>...
</manifest>

Android Bluetooth Device Discoverable Example

Following is the example of making device discoverable to other nearby Bluetooth devices on button click in android applications.

Create a new android application using android studio and give names as BluetoothDiscoverableExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
android:layout_width="match_parent"
    
android:layout_height="match_parent"
    
android:paddingLeft="10dp"
    
android:paddingRight="10dp">
    <
Button
        
android:id="@+id/btnOn"
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:text="Turn On" android:layout_marginLeft="50dp" android:layout_marginTop="200dp" />
    <
Button
        
android:id="@+id/btnDiscoverable"
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:layout_alignBottom="@+id/btnOn"
        
android:layout_toRightOf="@+id/btnOn"
        
android:text="Discoverable" />
    <
Button
        
android:id="@+id/btnOFF"
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:layout_alignBottom="@+id/btnDiscoverable"
        
android:layout_toRightOf="@+id/btnDiscoverable"
        
android:text="Turn OFF" />
</
RelativeLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.bluetoothdiscoverableexample path and write the code like as shown below

MainActivity.java

package com.tutlane.bluetoothdiscoverableexample;import android.bluetooth.BluetoothAdapter;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    
@Override
    
protected void onCreate(Bundle savedInstanceState) {
        
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        Button btntOn = (Button)findViewById(R.id.
btnOn);
        Button btntOff = (Button)findViewById(R.id.
btnOFF);
        Button btnDisc = (Button)findViewById(R.id.
btnDiscoverable);
        
final BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
        btntOn.setOnClickListener(
new View.OnClickListener() {
            
@Override
            
public void onClick(View v) {
                
if(bAdapter == null)
                {
                    Toast.makeText(getApplicationContext(),
"Bluetooth Not Supported",Toast.LENGTH_SHORT).show();
                }
                
else{
                    
if(!bAdapter.isEnabled()){
                        startActivityForResult(
new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),1);
                        Toast.makeText(getApplicationContext(),
"Bluetooth Turned ON",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        btntOff.setOnClickListener(
new View.OnClickListener() {
            
@Override
            
public void onClick(View v) {
                
bAdapter.disable();
                Toast.makeText(getApplicationContext(),
"Bluetooth Turned OFF", Toast.LENGTH_SHORT).show();
            }
        });
        btnDisc.setOnClickListener(
new View.OnClickListener() {
            
@Override
            
public void onClick(View v) {
                
if(!bAdapter.isDiscovering()){
                    startActivityForResult(
new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),1);
                    Toast.makeText(getApplicationContext(),
"Making Device Discoverable",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
If you observe above code, we are making sure our device discoverable to other devices using ACTION_REQUEST_DISCOVERABLE.

As discussed, we need to set Bluetooth permissions in android manifest file (AndroidManifest.xml) to access Bluetooth features in android applications. Now open android manifest file (AndroidManifest.xml) and write the code like as shown below

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    
package="com.tutlane.bluetoothdiscoverableexample">
    <
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:roundIcon="@mipmap/ic_launcher_round"
        
android:supportsRtl="true"
        
android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />
                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
    </
application>
</
manifest>
If you observe above code, we added required Bluetooth permissions in manifest file to access Bluetooth features in android applications.

Output of Android Bluetooth Device Discoverable Example

When we run above program in android studio we will get the result like as shown below.

 Android Bluetooth Device Discoverable with Example Result

When we click on Turn ON or Turn OFF buttons, we can make the device Bluetooth turn ON or OFF and when click on Discoverable button, our device discoverable to other Bluetooth devices.

This is how we can make our device discoverable to other nearby Bluetooth devices in android applications based on our requirements

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...