Altbeacon库无法找到/跟踪设备附近的传输信标

问题描述 投票:0回答:1

我正在使用altbeacon库进行联系人跟踪。但是当我的设备靠近其他扫描手机时,我无法找到/跟踪我的设备。我基本上有两部手机,一部用于扫描,另一部用作信标发射器。我可以从我的电话号码2发送信标。我也在“定位信标”应用程序中进行了测试。它显示了我的电话。但是,当我在电话号码1上进行测试时,它不起作用。即使正在调用didDetermineStateForRegiononBeaconServiceConnect,在任何日志上也看不到任何信标。

下面是我的应用程序类:

package com.example.mybeaconprojectaye

import android.app.*
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseSettings
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.RemoteException
import android.util.Log
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.altbeacon.beacon.*
import org.altbeacon.beacon.startup.BootstrapNotifier
import org.altbeacon.beacon.startup.RegionBootstrap
import java.util.*

class MyApplication : Application(), BootstrapNotifier, BeaconConsumer {


    val CHANNEL_ID = "myproximityservice"
    val CHANNEL_NAME = "My Proximity Service Channel"
    val backgroundBetweenScanPeriod = 6200L
    val backgroundScanPeriod = 3000L
    val TAG: String = "xoxo"
    val REGIONID = "rangeid"


    val uuidString: String= "id1"

    lateinit var beaconManager: BeaconManager
    private var regionBootstrap: RegionBootstrap? = null


    override fun onCreate() {
        super.onCreate()

        beaconManager = BeaconManager.getInstanceForApplication(this)
        setupBeaconScanning()
        beaconManager.bind(this)
    }

    override fun onBeaconServiceConnect() {

        Log.e(TAG, "Service connected ")
        val rangeNotifier = RangeNotifier { beacons, region ->
            if (beacons.size > 0) {
                Log.e(TAG, "found new beacons  " + beacons.size)
                for (beacon: Beacon in beacons){
                    Log.e(TAG,"New Beacon before condition check=${beacon.id2}-${beacon.id3}-${beacon.id1}")

                    GlobalScope.launch {

                        try {
                            val deviceUUID: String = beacon.id1.toString()
                            Log.e(TAG, "  before condition check=${deviceUUID}")
                                Log.e(
                                    TAG,
                                    "New Beacon=${beacon.id2}/${beacon.id3}/${beacon.id1}"
                                )
                              Log.e("xoxo","${beacon.id2}/${beacon.id3}/${beacon.id1} + "+ beacon.distance.toLong())


                                if (beacon.distance.toInt() < 2) {
                                    /*  val intentNotification = Intent(this@BeaconApp, HomeActivity::class.java)
                                  intentNotification.putExtra(Constants.DeviceConstants.IS_VIBRATOR, true)

                                  intentNotification.flags =
                                      Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

                                  startActivity(intentNotification)*/



                                    //sendSafetyNotification()



                            }
                        }catch (ex: Exception){

                            Log.e(TAG, "  EXCEPTION: "+ex.toString())

                        }

                    }
                }
                //  sendBroadcast(Intent(NEW_DEVICE_ACTION))
            }
        }
        try {
            beaconManager.startRangingBeaconsInRegion(
                Region(
                    REGIONID,
                    null,
                    null,
                    null
                )
            )
            beaconManager.addRangeNotifier(rangeNotifier)
        } catch (e: RemoteException) {
            e.printStackTrace()
        }

    }

    override fun didDetermineStateForRegion(state: Int, p1: Region?) {

        Log.e("xoxo", "didDetermineStateForRegion state: "+state )

    }

    override fun didEnterRegion(p0: Region?) {

        Log.e("xoxo", "i just saw a beacon")


    }

    override fun didExitRegion(p0: Region?) {
    }


    fun setupBeaconScanning() {
        beaconManager.beaconParsers.clear()

        val altbeaconParser =
            BeaconParser().setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25")
        altbeaconParser.setHardwareAssistManufacturerCodes(intArrayOf(0x0118))
        beaconManager.beaconParsers
            .add(altbeaconParser)

        val iBeaconParser =
            BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")
        iBeaconParser.setHardwareAssistManufacturerCodes(intArrayOf(0x004c))

        beaconManager.beaconParsers
            .add(iBeaconParser)
        beaconManager.beaconParsers
            .add(BeaconParser().setBeaconLayout(BeaconParser.URI_BEACON_LAYOUT))
        beaconManager.beaconParsers
            .add(BeaconParser().setBeaconLayout(BeaconParser.EDDYSTONE_TLM_LAYOUT))
        beaconManager.beaconParsers
            .add(BeaconParser().setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT))
        beaconManager.beaconParsers
            .add(BeaconParser().setBeaconLayout(BeaconParser.EDDYSTONE_URL_LAYOUT))


        /* beaconManager.beaconParsers
             .add(BeaconParser().setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"))
         beaconManager.beaconParsers
             .add(BeaconParser().setBeaconLayout("s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19"))
         beaconManager.beaconParsers
             .add(BeaconParser().setBeaconLayout("x,s:0-1=feaa,m:2-2=20,d:3-3,d:4-5,d:6-7,d:8-11,d:12-15"))
         beaconManager.beaconParsers
             .add(BeaconParser().setBeaconLayout("s:0-1=feaa,m:2-2=10,p:3-3:-41,i:4-20v"))
         beaconManager.beaconParsers
             .add(BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"))
         beaconManager.beaconParsers
             .add(BeaconParser().setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"))
         beaconManager.beaconParsers
             .add(BeaconParser().setBeaconLayout("m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24"))


 */
        BeaconManager.setDebug(false)


        val builder = Notification.Builder(this)
        builder.setSmallIcon(R.drawable.ic_launcher_background)
        builder.setContentTitle("Proximity Service Running")
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
        )
        builder.setContentIntent(pendingIntent)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT
            )
            channel.description = "Used for scanning near by device"
            val notificationManager = getSystemService(
                Context.NOTIFICATION_SERVICE
            ) as NotificationManager
            notificationManager.createNotificationChannel(channel)
            builder.setChannelId(channel.id)
        }
        beaconManager.enableForegroundServiceScanning(builder.build(), 456)

        // For the above foreground scanning service to be useful, you need to disable
        // JobScheduler-based scans (used on Android 8+) and set a fast background scan
        // cycle that would otherwise be disallowed by the operating system.


        beaconManager.setEnableScheduledScanJobs(false)
        beaconManager.backgroundBetweenScanPeriod = backgroundBetweenScanPeriod
        beaconManager.backgroundScanPeriod = backgroundScanPeriod

        Log.d(TAG, "setting up background monitoring for beacons and power saving")
        // wake up the app when a beacon is seen
        // wake up the app when a beacon is seentitle getting
        val region = Region(
            REGIONID,
            null, null, null
        )
        regionBootstrap = RegionBootstrap(this, region)
    }


    fun startAdvertising(listener: AdvertiseListener):Boolean {

        val result = BeaconTransmitter.checkTransmissionSupported(this)
        Log.e("xoxo", "BLE TRANSMITTER STATUS " +(result== BeaconTransmitter.SUPPORTED).toString())
        if (BeaconTransmitter.SUPPORTED != result)
            return false
        val beacon = Beacon.Builder()
            .setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
            .setId2("1")
            .setId3("2")
            .setManufacturer(0x0118) // Radius Networks.  Change this for other beacon layouts
            .setTxPower(-59)
            .setDataFields(Arrays.asList(*arrayOf(0L))) // Remove this for beacon layouts without d: fields
            .build()


        // Change the layout below for other beacon types
        val beaconParser = BeaconParser()
            .setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25")
        val beaconTransmitter =
            BeaconTransmitter(applicationContext, beaconParser)
        beaconTransmitter.startAdvertising(beacon, object : AdvertiseCallback() {
            override fun onStartFailure(errorCode: Int) {
                Log.e(TAG, "Advertisement start failed with code: $errorCode")
                listener.onAdvertiseStatus(false)
            }

            override fun onStartSuccess(settingsInEffect: AdvertiseSettings) {
                Log.e(TAG, "Advertisement start succeeded. uuid"+uuidString)
                listener.onAdvertiseStatus(true)

            }
        })
        return true
    }


    interface AdvertiseListener{
        fun onAdvertiseStatus(success:Boolean)
    }

}

和我的MainActivity:

package com.example.mybeaconprojectaye

import android.Manifest
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import org.altbeacon.beacon.BeaconTransmitter

class MainActivity : AppCompatActivity() {

    companion object {
        private const val PERMISSION_REQUEST_FINE_LOCATION = 1
        private const val PERMISSION_REQUEST_BACKGROUND_LOCATION = 2
    }

    val TAG = "xoxo"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var result : Int = BeaconTransmitter.checkTransmissionSupported(this@MainActivity)

        Log.e("xoxo", "result: "+result)



        btn.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {

                requestPerms()


            }
        })

    }


    fun requestPerms() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    if (checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                        != PackageManager.PERMISSION_GRANTED
                    ) {
                        val builder =
                            AlertDialog.Builder(this)
                        builder.setTitle("Location is off")
                        builder.setMessage("Please allow location permission.")
                        builder.setPositiveButton(android.R.string.ok, null)
                        builder.setOnDismissListener {
                            requestPermissions(
                                arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
                                PERMISSION_REQUEST_BACKGROUND_LOCATION
                            )
                        }
                        builder.show()
                    } else startAdvertiseBeacons()

                } else startAdvertiseBeacons()
            } else {
                requestPermissions(
                    arrayOf(
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION
                    ),
                    PERMISSION_REQUEST_FINE_LOCATION
                )
            }
        } else startAdvertiseBeacons()
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            PERMISSION_REQUEST_FINE_LOCATION -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "fine location permission granted")
                    requestPerms()
                } else {
                    val builder =
                        AlertDialog.Builder(this)
                    builder.setTitle("Functionality limited")
                    builder.setMessage("Since location access has not been granted, this app will not be able to discover devices.")
                    builder.setPositiveButton(android.R.string.ok, null)
                    builder.setOnDismissListener { }
                    builder.show()
                }
                return
            }
            PERMISSION_REQUEST_BACKGROUND_LOCATION -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "background location permission granted")
                    requestPerms()
                } else {
                    val builder =
                        AlertDialog.Builder(this)
                    builder.setTitle("Functionality limited")
                    builder.setMessage("Since background location access has not been granted, this app will not be able to discover devices when in the background.")
                    builder.setPositiveButton(
                        android.R.string.ok,
                        DialogInterface.OnClickListener { dialog, which ->
                            dialog.cancel()
                            requestPerms()
                        })
                    builder.setOnDismissListener {
                        requestPerms()
                    }
                    builder.show()
                }
                return
            }
        }
    }

    private fun startAdvertiseBeacons() {
        (application as MyApplication).startAdvertising(object : MyApplication.AdvertiseListener {
            override fun onAdvertiseStatus(success: Boolean) {

            }
        })
    }

}

这是所有正在打印的日志:

2020-06-07 05:20:25.566 23822-23822/? E/libc: Access denied finding property "persist.vendor.sys.activitylog"
2020-06-07 05:20:26.468 23822-23822/com.example.mybeaconprojectaye E/xoxo: result: 0
2020-06-07 05:20:26.810 23822-23822/com.example.mybeaconprojectaye E/xoxo: Service connected 
2020-06-07 05:20:26.848 23822-23822/com.example.mybeaconprojectaye E/xoxo: didDetermineStateForRegion state: 0

任何人都可以告诉我我做错了什么,或者缺少某些步骤。我尝试研究关于stackoverflow的其他答案,但这是唯一一个在所有答案中到处都可以看到新类和接口的库。太混乱了。

P.S。

我正在尝试制作联系人跟踪应用。任何其他图书馆或您可以建议的东西也将不胜感激。

android android-studio bluetooth-lowenergy altbeacon eddystone
1个回答
0
投票

尝试颠倒手机1和2进行测试。如果使用BeaconScope进行扫描,它可以看到电话1&2的传输情况吗?如果您使用BeaconScope进行传输,则电话1或2上的应用程序都能看到信标传输吗?

如果无法在一个或两个电话上检测到信标范围,请检查应用权限以确认已将位置权限授予您的应用。转到设置->应用程序->您的应用程序,然后检查授予的权限。

还要检查是否已在手机上全局启用位置并且蓝牙已打开。

© www.soinside.com 2019 - 2024. All rights reserved.