首页 > 解决方案 > 如何显示串口蓝牙的rssi?

问题描述

我已经使用 android studio 制作了一个应用程序来连接到我的 Hc 05 蓝牙。接下来我想在我的 android 应用程序中显示 HC 05 的 rssi。

我正在使用 SPP 蓝牙库来管理我的应用程序中的蓝牙通信。我已经在互联网上冲浪以了解如何在 android 中显示已连接的串行蓝牙的 rssi,但一无所获。希望你们能帮助我这是我的 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);
    }


}

我的清单

<?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>

我的布局

<?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>

标签: androidarduinobluetoothrssihc-05

解决方案


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);
            }
        }
    };

使用 rssi

int  rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);

推荐阅读