Blog purpose for android basic example for android app developer. any query please my contact

Saturday 11 April 2020

android studio bluetooth demo example


In this Article Today learn android studio bluetooth demo example This example provides a demonstration of BluetoothAdapter class to manipulate .


Among many ways, Bluetooth is a way to send or receive data between two different devices. Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices.


for the more information to visit  this link https://developer.android.com/guide/topics/connectivity/bluetooth


Android provides Bluetooth API to perform these different operations.


Scan for other Bluetooth devices


Get a list of paired devices


Connect to other devices through service discovery


Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling the static method getDefaultAdapter(). Its syntax is given below.






1.MainActivity.java:


package com.akash.bluetoothdemo;


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.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ListView;

import android.widget.Toast;


public class MainActivity extends Activity {

    protected static final String TAG = "bluetoothdemo";

    int REQUEST_ENABLE_BT = 1;

    EditText main;

    private ArrayAdapter<String> mNewDevicesArrayAdapter;


    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        main = (EditText) findViewById(R.id.mainTextArea);

        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.string.app_name);


        // Hook up the Discover button to its handler

        Button discover = (Button) findViewById(R.id.discoverButton);

        discover.setOnClickListener(discoverButtonHandler);


        // Hook up the ArrayAdapter to the ListView

        ListView lv = (ListView) findViewById(R.id.pairedBtDevices);

        lv.setAdapter(mNewDevicesArrayAdapter);


        BluetoothAdapter BT = BluetoothAdapter.getDefaultAdapter();

        if (BT == null) {

            String noDevMsg = "This device does not appear to have a Bluetooth adapter, sorry";

            main.setText(noDevMsg);

            Toast.makeText(this, noDevMsg, Toast.LENGTH_LONG).show();

            return;

        }

        if (!BT.isEnabled()) {

            // Ask user's permission to switch the Bluetooth adapter On.

            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);

        }

    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode==REQUEST_ENABLE_BT) {

            if (resultCode==Activity.RESULT_OK) {

                BluetoothAdapter BT = BluetoothAdapter.getDefaultAdapter();

                String address = BT.getAddress();

                String name = BT.getName();

                String connectedMsg = "BT is on; your device is "  + name + " : " + address;

                main.setText(connectedMsg);

                Toast.makeText(this, connectedMsg, Toast.LENGTH_LONG).show();

                Button discoverButton = (Button) findViewById(R.id.discoverButton);

                discoverButton.setOnClickListener(discoverButtonHandler);

            } else {

                Toast.makeText(this, "Failed to enable Bluetooth adapter!", Toast.LENGTH_LONG).show();

            }

        } else {

            Toast.makeText(this, "Unknown RequestCode " + requestCode, Toast.LENGTH_LONG).show();

        }

    }


    /** When the user clicks the Discover button, get the list of paired devices

     */

    OnClickListener discoverButtonHandler = new OnClickListener() {

        @Override

        public void onClick(View v) {

            Log.d(TAG, "in onClick(" + v + ")");

            // IntentFilter for found devices

            IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

            // Broadcast receiver for any matching filter

            MainActivity.this.registerReceiver(mReceiver, foundFilter);


            IntentFilter doneFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

            MainActivity.this.registerReceiver(mReceiver, doneFilter);

        }

    };


    protected void onDestroy() {

        unregisterReceiver(mReceiver);

        super.onDestroy();

    }


    /** Receiver for the BlueTooth Discovery Intent; put the paired devices

     * into the viewable list.

     */

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override

        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            Log.d(TAG, "in onReceive, action = " + action);


            if (BluetoothDevice.ACTION_FOUND.equals(action)){

                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);


                if(btDevice.getBondState() != BluetoothDevice.BOND_BONDED){

                    // XXX use a better type and a Layout in the visible list

                    mNewDevicesArrayAdapter.add(btDevice.getName()+"\n"+btDevice.getAddress());

                }

            }

            else

            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

                setProgressBarIndeterminateVisibility(false);

                setTitle(R.string.select_device);

                if (mNewDevicesArrayAdapter.getCount() == 0){

                    String noDevice = getResources().getText(R.string.none_paired).toString();

                    mNewDevicesArrayAdapter.add(noDevice);

                }

            }

        }

    };

}




2.activity_main.xml:


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

    <EditText

        android:id="@+id/mainTextArea"

        android:editable="false"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/Bluettoth"

        />

    <ListView

        android:id="@+id/pairedBtDevices"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        />

    <Button

        android:id="@+id/discoverButton"

        android:text="@string/discover"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        />

</LinearLayout>



3.strings.xml:


<resources>
    <string name="app_name">Bluetooth Demo</string>
    <string name="Bluettoth">Bluettoth</string>
    <string name="discover">discover</string>
    <string name="select_device">select_device</string>
    <string name="none_paired">none_paired</string>
</resources>


4.AndroidManifest.xml:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.akash.bluetoothdemo">
    <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>



5.Output:



android studio bluetooth demo example

No comments:

Post a Comment