0

I've made an app using android studio to connect to my Hc 05 Bluetooth. Next i want to show rssi of HC 05 in my android app.

I am using SPP Bluetooth library to manage my bluetooth communication in my app. i have surfed in internet to how to show rssi of connected serial bluetooth in android but found nothing. Hope you guys can help me out This is my Mainactivity.Java

package com.yuda.user.bluetoothaplikasidua;

import android.app.Activity;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;

import android.media.RingtoneManager;
import android.net.Uri;

import android.os.Handler;
import android.support.v4.app.NotificationCompat;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import app.akexorcist.bluetotohspp.library.BluetoothSPP;
import app.akexorcist.bluetotohspp.library.BluetoothState;
import app.akexorcist.bluetotohspp.library.DeviceList;


public class MainActivity extends AppCompatActivity {

    BluetoothSPP bluetooth;

    Button connect;

    private PendingIntent pendingIntent;
    private NotificationManager notificationManager;
    private NotificationCompat.Builder notificationBuilder;
    NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //create Intent
        Intent myIntent = new Intent(this, MainActivity.class);
        //Initialize PendingIntent
        pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);
        //Initialize NotificationManager using Context.NOTIFICATION_SERVICE
        notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bluetooth = new BluetoothSPP(this);

        connect = (Button) findViewById(R.id.connect);
//        on = (Button) findViewById(R.id.on);
//        off = (Button) findViewById(R.id.off);

        if (!bluetooth.isBluetoothAvailable()) {
            Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();
            finish();
        }

        bluetooth.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
            public void onDeviceConnected(String name, String address)
            {
                connect.setText("Connected to " + name);
                connect.setBackgroundColor(getResources().getColor(R.color.connectedColor));
                notification2();

            }

            public void onDeviceDisconnected()
            {
                connect.setText("Connection lost");
                connect.setBackgroundColor(getResources().getColor(R.color.disconnectedColor));
                notification();
            }

            public void onDeviceConnectionFailed()
            {
                connect.setText("Unable to connect");
                connect.setBackgroundColor(getResources().getColor(R.color.unconnectedColor));
            }
        });

        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bluetooth.getServiceState() == BluetoothState.STATE_CONNECTED) {
                    bluetooth.disconnect();
                } else {

                    Intent intent = new Intent(getApplicationContext(), DeviceList.class);
                    startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);


//                    connect.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.colorPrimaryDark));
                }
            }
        });

//        on.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                bluetooth.send(ON, true);
//            }
//        });
//
//        off.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                bluetooth.send(OFF, true);
//            }
//        });

    }


    public void onStart() {
        super.onStart();
        if (!bluetooth.isBluetoothEnabled()) {
            bluetooth.enable();
            Toast.makeText(getApplicationContext(), "Enabling Bluetooh...", Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), "Bluetooth enabled!", Toast.LENGTH_SHORT).show();
        } else {
            if (!bluetooth.isServiceAvailable()) {
                bluetooth.setupService();
                bluetooth.startService(BluetoothState.DEVICE_OTHER);
                Toast.makeText(getApplicationContext(), "Bluetooth already enabled!", Toast.LENGTH_SHORT).show();
            }
        }
    }


    public void onDestroy() {
        super.onDestroy();
        bluetooth.stopService();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
            if (resultCode == Activity.RESULT_OK)
                bluetooth.connect(data);
        } else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                bluetooth.setupService();
            } else {
                Toast.makeText(getApplicationContext()
                        , "Bluetooth was not enabled."
                        , Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    public void notification()
    {

        //create Intent
        Intent myIntent = new Intent(this, NotificationActivity.class);
        //Initialize PendingIntent
        pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);

        //Prepare Notification Builder

        notificationBuilder  = new NotificationCompat.Builder(MainActivity.this)
                .setSmallIcon(R.drawable.notif)
                .setPriority(NotificationCompat.PRIORITY_HIGH)


       .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setFullScreenIntent(pendingIntent, true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.appicon))
            .setContentTitle("WARNING!!!").setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pendingIntent)

            .setContentText("You have lost your child!");


    Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    notificationBuilder.setSound(uri);

    //set notification on lock screen
    notificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

    //add lights
    notificationBuilder.setLights(Color.RED, 500, 500);

    //add vibrate { delay, vibrate, sleep, vibrate, sleep } pattern.
    long[] v = {0,1000};
    notificationBuilder.setVibrate(v);
    notificationManager.notify(1, notificationBuilder.build());

}


public void notification2()
{

    //create Intent
    Intent myIntent = new Intent(this, MainActivity.class);
    //Initialize PendingIntent
    pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);

    //Prepare Notification Builder

    notificationBuilder  = new NotificationCompat.Builder(MainActivity.this)
            .setSmallIcon(R.drawable.notif)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.appicon))
            .setContentTitle("Proyek Akhir - Bluetooth").setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pendingIntent)

            .setContentText("Device Connected");
    long[] v = {0,500};
    notificationBuilder.setVibrate(v);
    notificationManager.notify(1, notificationBuilder.build());

    Handler h = new Handler();
    long delayInMilliseconds = 2000;
    h.postDelayed(new Runnable() {
        public void run() {
            notificationManager.cancel(1);
        }
    }, delayInMilliseconds);
    }


}

My Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yuda.user.bluetoothappas">
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
    <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" />
                <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
                <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

My layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@android:color/white"
    tools:context="com.yuda.user.bluetoothaplikasidua.MainActivity">

    <Button
        android:id="@+id/connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:baselineAligned="true"
        android:text="@string/connect"
        android:textColor="@android:color/white"
        />

    <!--<Button-->
    <!--android:id="@+id/on"-->
    <!--android:layout_width="match_parent"-->
    <!--android:layout_height="wrap_content"-->
    <!--android:text="@string/led_on" />-->

    <!--<Button-->
    <!--android:id="@+id/off"-->
    <!--android:layout_width="match_parent"-->
    <!--android:layout_height="wrap_content"-->
    <!--android:text="@string/led_off" />-->

</LinearLayout>
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Yuda_Ihza
  • 19
  • 3

1 Answers1

0

from DeviceList.java

// The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                //to get rssi
                int  rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
                Toast.makeText(getApplicationContext(),"  RSSI: " + rssi + "dBm", Toast.LENGTH_SHORT).show()

                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    String strNoFound = getIntent().getStringExtra("no_devices_found");
                    if(strNoFound == null) 
                        strNoFound = "No devices found";                    

                    if(mPairedDevicesArrayAdapter.getItem(0).equals(strNoFound)) {
                        mPairedDevicesArrayAdapter.remove(strNoFound);
                    }
                    mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }

            // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                String strSelectDevice = getIntent().getStringExtra("select_device");
                if(strSelectDevice == null) 
                    strSelectDevice = "Select a device to connect";
                setTitle(strSelectDevice);
            }
        }
    };

to get rssi use

int  rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
APP
  • 445
  • 1
  • 3
  • 16