为什么即使在定位应用程序中,我的应用程序中也检测不到任何信标?

问题描述

我正在使用信标开发室内导航,该应用程序有两个按钮(统计按钮和停止按钮)来启动和停止读取信标,该应用程序运行良好,但无法检测到任何显示“未找到信标”的信标,我在堆栈溢出中执行相同的示例代码但它不起作用,你能帮我解决这个问题吗?注意:我使用的是 Feasy Beacon。

这是我的主要活动:

public class MainActivity extends AppCompatActivity implements View.OnClickListener,BeaconConsumer,RangeNotifier  {

    protected final String TAG = MainActivity.this.getClass().getSimpleName();;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private static final int REQUEST_ENABLE_BLUetoOTH = 1;
    private static final long DEFAULT_SCAN_PERIOD_MS = 6000l;
    private static final String ALL_BEACONS_REGION = "AllBeaconsRegion";

    private BeaconManager mBeaconManager;

    private Region mRegion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getStartButton().setonClickListener(this);
        getStopButton().setonClickListener(this);

        mBeaconManager = BeaconManager.getInstanceForApplication(this);

        mBeaconManager.getBeaconParsers().add(new BeaconParser().
                setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));

        ArrayList<Identifier> identifiers = new ArrayList<>();

        mRegion = new Region(ALL_BEACONS_REGION,identifiers);
    }

    @Override
    public void onClick(View view) {

        if (view.equals(findViewById(R.id.startReadingBeaconsButton))) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) !=
                        PackageManager.PERMISSION_GRANTED) {

                    askForLocationPermissions();

                } else { 
                    //Location permissions granted

                    prepareDetection();
                }

            } else { 
                // Android versions <6

                prepareDetection();
            }

        } else if (view.equals(findViewById(R.id.stopReadingBeaconsButton))) {

            stopDetectingBeacons();

            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            if (mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.disable();
            }
        }
    }

    /**
     *
     * Activate location and bluetooth to start detecting beacons
     */
    private void prepareDetection() {

        if (!isLocationEnabled()) {

            askToTurnOnLocation();

        } else { 
            // Location on,let's check the bluetooth

            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            if (mBluetoothAdapter == null) {

                showToastMessage("This device does not support bluetooth,it is not possible to search for beacons");

            } else if (mBluetoothAdapter.isEnabled()) {

                startDetectingBeacons();

            } else {

                //Ask the user to activate bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent,REQUEST_ENABLE_BLUetoOTH);
            }
        }
    }

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

        if (requestCode == REQUEST_ENABLE_BLUetoOTH) {

            // User has activated bluetooth
            if (resultCode == RESULT_OK) {

                startDetectingBeacons();

            } else if (resultCode == RESULT_CANCELED) { // User refuses to enable bluetooth

                showToastMessage("With bluetooth deactivated,it is not possible to search for beacons");
            }
        }

        super.onActivityResult(requestCode,resultCode,data);
    }

    /**
     * * Start detecting beacons,hiding or showing the corresponding buttons
     */
    private void startDetectingBeacons() {

   // Set a scan period
        mBeaconManager.setForegroundScanPeriod(DEFAULT_SCAN_PERIOD_MS);

        // Link to the beacon service. Get a callback when it's ready to be used
        mBeaconManager.bind(this);
        System.out.println("beacon manager bind  = " + mBeaconManager.isBound(this));

        // disable start button
        getStartButton().setEnabled(false);
        getStartButton().setAlpha(.5f);

        // Activate stop button
        getStopButton().setEnabled(true);
        getStopButton().setAlpha(1);
    }

    @Override
    public void onBeaconServiceConnect() {

        try {
            //// Start looking for beacons that match the last Region object,including
            //     updates on the estimated distance
            mBeaconManager.startRangingBeaconsInRegion(mRegion);
            mBeaconManager.startMonitoringBeaconsInRegion(mRegion);


            showToastMessage("Starting to look for beacons");

        } catch (remoteexception e) {
            Log.d(TAG,"An exception occurred while starting to search for beacons " + e.getMessage());
        }

        mBeaconManager.addRangeNotifier(this);
    }


    /**
     *
     * Method called every DEFAULT_SCAN_PERIOD_MS seconds with beacons detected during that period
     */
    @Override
    public void didRangeBeaconsInRegion(Collection<Beacon> beacons,Region region) {

        if (beacons.size() == 0) {
            showToastMessage("No beacons found");
        }

        for (Beacon beacon : beacons) { 
            showToastMessage("Offer number% 1 $ s detected !!   beacon.getId3 = "+ beacon.getId3());
        }
    }

    private void stopDetectingBeacons() {

        try {
            mBeaconManager.stopMonitoringBeaconsInRegion(mRegion);
            showToastMessage("Stopping the search for beacons");
        } catch (remoteexception e) {
            Log.d(TAG,"An exception occurred while stopping searching for beacons " + e.getMessage());
        }

        mBeaconManager.removeAllRangeNotifiers();

        // Unbind service from beacons
        mBeaconManager.unbind(this);

        // Activate start button
        getStartButton().setEnabled(true);
        getStartButton().setAlpha(1);

        // disable stop button
        getStopButton().setEnabled(false);
        getStopButton().setAlpha(.5f);
    }

    /**
     * * Check location permission for Android> = M
     */
    private void askForLocationPermissions() {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("This application needs access to the location");
        builder.setMessage("Please grant location permissions so that the application can detect beacons");
        builder.setPositiveButton(android.R.string.ok,null);
        builder.setondismissListener(new DialogInterface.OndismissListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            public void ondismiss(DialogInterface dialog) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_REQUEST_COARSE_LOCATION);
            }
        });
        builder.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[],int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    prepareDetection();
                } else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Limited functionality");
                    builder.setMessage("Since the locate permission has not been granted" +
                            "this application will not be able to search for beacons");
                    builder.setPositiveButton(android.R.string.ok,null);
                    builder.setondismissListener(new DialogInterface.OndismissListener() {
                        @Override
                        public void ondismiss(DialogInterface dialog) {

                        }
                    });
                    builder.show();
                }
                return;
            }
        }
    }

    /**
     *
     * @return true si la localización esta activada,false en caso contrario
     */
    private boolean isLocationEnabled() {

        LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        boolean networkLocationEnabled = false;

        boolean gpsLocationEnabled = false;

        try {
            networkLocationEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            gpsLocationEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

        } catch (Exception ex) {
            Log.d(TAG,"Exception when obtaining location information");
        }

        return networkLocationEnabled || gpsLocationEnabled;
    }

    private void askToTurnOnLocation() {

        // Notificar al usuario
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("Localization in high precision mode not activated");
        dialog.setPositiveButton("Open location settings",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface,int paramInt) {
                // Todo Auto-generated method stub
                Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(myIntent);
            }
        });
        dialog.show();
    }

    private Button getStartButton() {
        return (Button) findViewById(R.id.startReadingBeaconsButton);
    }

    private Button getStopButton() {
        return (Button) findViewById(R.id.stopReadingBeaconsButton);
    }

    private void showToastMessage (String message) {
        Toast toast = Toast.makeText(this,message,Toast.LENGTH_LONG);
        toast.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBeaconManager.removeAllRangeNotifiers();
        mBeaconManager.unbind(this);
    }

在 Manifest.xml 中我使用了这些权限:


    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.BLUetoOTH" />
    <uses-permission android:name="android.permission.BLUetoOTH_ADMIN" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

代码的Logcat输出

I/DecorView: [INFO] isPopOver=false,config=true
    updateCaptionType >> DecorView@651b67b[],isFloating=false,isApplication=true,hasWindowDecorCaption=false,hasWindowControllerCallback=true
D/DecorView: setCaptionType = 0,this = DecorView@651b67b[]
W/ndoornavigatio: Unsupported class loader
W/ndoornavigatio: Unsupported class loader
I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:46 and remote module com.google.android.gms.measurement.dynamite:45
    Selected local version of com.google.android.gms.measurement.dynamite
W/ndoornavigatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist,reflection,allowed)
    Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist,allowed)
I/BeaconManager: BeaconManager started up on pid 32407 named 'com.example.indoornavigation' for application package 'com.example.indoornavigation'.  isMainProcess=true
D/BeaconParser: Parsing beacon layout: m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25
D/BeaconParser: Parsing beacon layout: s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19
D/InputTransport: Input channel constructed: 'd587e8c',fd=79
I/ViewRootImpl@541c6e9[MainActivity]: setView = com.android.internal.policy.DecorView@651b67b TM=true
V/FA: onActivityCreated
I/ViewRootImpl@541c6e9[MainActivity]: Relayout returned: old=(0,1080,2400) new=(0,2400) req=(1080,2400)0 dur=5 res=0x7 s={true 520873524992} ch=true fn=-1
I/mali_winsys: new_window_surface() [1080x2400] return: 0x3000
I/ViewRootImpl@541c6e9[MainActivity]: [DP] dp(1) 1 android.view.ViewRootImpl.reportNextDraw:10665 android.view.ViewRootImpl.performTraversals:3725 android.view.ViewRootImpl.doTraversal:2511 
    [DP] pd() Asnyc report
I/Gralloc4: mapper 4.x is not supported
W/Gralloc3: mapper 3.x is not supported
I/gralloc: Arm Module v1.0
I/ViewRootImpl@541c6e9[MainActivity]: [DP] pdf(0) 1 android.view.ViewRootImpl.lambda$performDraw$1$ViewRootImpl:4546 android.view.-$$Lambda$ViewRootImpl$DJd0VUYJgsebcnSohO6h8zc_ONI.run:6 android.os.Handler.handleCallback:938 
    [DP] rdf()
I/ViewRootImpl@541c6e9[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1 1
D/InputMethodManager: prepareNavigationBarInfo() DecorView@651b67b[MainActivity]
    getNavigationBarColor() -855310
    prepareNavigationBarInfo() DecorView@651b67b[MainActivity]
    getNavigationBarColor() -855310
V/InputMethodManager: Starting input: tba=com.example.indoornavigation ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true,NavVisible : true,NavTrans : false
D/InputMethodManager: startInputInner - Id : 0
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport: Input channel constructed: 'ClientS',fd=84
D/InputMethodManager: prepareNavigationBarInfo() DecorView@651b67b[MainActivity]
    getNavigationBarColor() -855310
V/InputMethodManager: Starting input: tba=com.example.indoornavigation ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true,NavTrans : false
D/InputMethodManager: startInputInner - Id : 0
D/SurfaceControl: hide : Surface(name=Surface(name=26f5368 InputMethod)/@0xac28067 - animation-leash)/@0x397f654
    nativeSetFlags Done : Surface(name=Surface(name=26f5368 InputMethod)/@0xac28067 - animation-leash)/@0x397f654
D/SurfaceControl: release : Surface(name=Surface(name=4bc02eb NavigationBar0)/@0xbdb6954 - animation-leash)/@0xdb9a9fd
I/SurfaceControl: nativeRelease nativeObject s[516041601648]
    nativeRelease nativeObject e[516041601648]
D/SurfaceControl: release : Surface(name=Surface(name=60657fa StatusBar)/@0x60c7d6f - animation-leash)/@0x86a6f2
I/SurfaceControl: nativeRelease nativeObject s[516041601760]
    nativeRelease nativeObject e[516041601760]
V/FA: App measurement collection enabled
V/FA: App measurement enabled for app package,google app id: com.example.indoornavigation,1:249328161647:android:76a143ad7a30d3f99a0e9a
I/FA: App measurement initialized,version: 39000
    To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
      adb shell setprop debug.firebase.analytics.app com.example.indoornavigation
D/FA: Debug-level message logging enabled
V/FA: Connecting to remote service
V/FA: Detected application was in foreground
V/FA: Session started,time: 1309590020
V/FA: Connection attempt already in progress
I/FA: Tag Manager is not found and thus will not be used
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
    Activity resumed,time: 1309589939
V/FA: Connection attempt already in progress
    Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 7
I/ViewRootImpl@541c6e9[MainActivity]: ViewPostIme pointer 0
I/ViewRootImpl@541c6e9[MainActivity]: ViewPostIme pointer 1
I/ScanJob: Using immediateScanJobId from manifest: 208352939
I/ScanJob: Using periodicScanJobId from manifest: 208352940
W/JobInfo: Requested interval +5m0s0ms for job 208352940 is too small; raising to +15m0s0ms
    Requested flex 0 for job 208352940 is too small; raising to +5m0s0ms
I/ScanJob: Using immediateScanJobId from manifest: 208352939
I/ScanJob: Using periodicScanJobId from manifest: 208352940
W/JobInfo: Requested interval +5m0s0ms for job 208352940 is too small; raising to +15m0s0ms
    Requested flex 0 for job 208352940 is too small; raising to +5m0s0ms
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10428; state: ENABLED
I/Toast: show: focusdisplayId = 0,isFocusInDesktop = false mCustomdisplayId=-1 isDexDualMode=false
    show: isActivityContext = true
I/System.out: beacon manager bind  = true
I/CycledLeScanner: Using Android O scanner
I/ScanJob: Using immediateScanJobId from manifest: 208352939
    Running immediate scan job: instance is org.altbeacon.beacon.service.ScanJob@64e6401
    scanJob version 2.17.1 is starting up on the main process
W/ModelSpecificdistanceCalculator: Cannot find match for this device.  Using default
    Cannot find match for this device.  Using default
D/BluetoothAdapter: STATE_ON
D/BluetoothAdapter: STATE_ON
D/BluetoothLeScanner: Stop Scan with callback intent
D/BluetoothAdapter: STATE_ON
I/ScanJob: Scan job running for 300000 millis
D/BluetoothAdapter: STATE_ON
D/BluetoothLeScanner: Start Scan with callback
D/BluetoothLeScanner: onScannerRegistered() - status=0 scannerId=15 mScannerId=0
V/FA: Inactivity,disconnecting from the service
D/BluetoothAdapter: STATE_ON
D/BluetoothLeScanner: Stop Scan with callback
D/BluetoothAdapter: STATE_ON
I/Toast: show: focusdisplayId = 0,isFocusInDesktop = false mCustomdisplayId=-1 isDexDualMode=false
    show: isActivityContext = true
D/BluetoothLeScanner: Start Scan with callback
D/BluetoothLeScanner: onScannerRegistered() - status=0 scannerId=15 mScannerId=0
D/BluetoothAdapter: STATE_ON
I/Toast: show: focusdisplayId = 0,isFocusInDesktop = false mCustomdisplayId=-1 isDexDualMode=false
    show: isActivityContext = true
E/CycledLeScannerForLollipop: Scan Failed: a BLE scan with the same settings is already started by the app
I/ViewRootImpl@541c6e9[MainActivity]: ViewPostIme pointer 0
I/ViewRootImpl@541c6e9[MainActivity]: ViewPostIme pointer 1
I/ScanJob: Using immediateScanJobId from manifest: 208352939
I/ScanJob: Using periodicScanJobId from manifest: 208352940
W/JobInfo: Requested interval +5m0s0ms for job 208352940 is too small; raising to +15m0s0ms
    Requested flex 0 for job 208352940 is too small; raising to +5m0s0ms
I/Toast: show: focusdisplayId = 0,isFocusInDesktop = false mCustomdisplayId=-1 isDexDualMode=false
    show: isActivityContext = true
I/BeaconManager: Cancelling scheduled jobs after unbind of last consumer.
I/ScanJob: Using immediateScanJobId from manifest: 208352939
I/ScanJob: Using periodicScanJobId from manifest: 208352940
D/BluetoothAdapter: disable()
I/ScanJob: Using periodicScanJobId from manifest: 208352940
    onStopJob called for immediate scan org.altbeacon.beacon.service.ScanJob@64e6401
D/BluetoothAdapter: STATE_ON
D/BluetoothAdapter: STATE_ON
D/BluetoothLeScanner: Stop Scan with callback intent
W/ScanHelper: Failed to start background scan on Android O: BluetoothAdapter is not enabled
D/BluetoothAdapter: onBluetoothStateChange: up=false
    Bluetooth is turned off,stop adv
D/BluetoothAdapter: There are no active google scan apps,stop scan
D/BluetoothLeScanner: stopAllScan standalone boolean value is = false
D/BluetoothLeScanner: Exiting stopping all callback scans
D/BluetoothAdapter: ondisableBLE
    There are no active google scan apps,stop scan
D/BluetoothLeScanner: stopAllScan standalone boolean value is = false
    Exiting stopping all callback scans
I/ViewRootImpl@541c6e9[MainActivity]: ViewPostIme pointer 0
V/FA: Recording user engagement,ms: 16278
V/FA: Connecting to remote service
V/FA: Activity paused,time: 1309606218
I/ViewRootImpl@541c6e9[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 1
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 2
D/SurfaceControl: release : Surface(name=Surface(name=26f5368 InputMethod)/@0xac28067 - animation-leash)/@0x397f654
I/SurfaceControl: nativeRelease nativeObject s[516041547664]
    nativeRelease nativeObject e[516041547664]
D/SurfaceControl: release : Surface(name=Surface(name=4bc02eb NavigationBar0)/@0xbdb6954 - animation-leash)/@0xfc04cdb
I/SurfaceControl: nativeRelease nativeObject s[516041551024]
    nativeRelease nativeObject e[516041551024]
D/SurfaceControl: release : Surface(name=Surface(name=60657fa StatusBar)/@0x60c7d6f - animation-leash)/@0x8ada378
I/SurfaceControl: nativeRelease nativeObject s[516041551360]
    nativeRelease nativeObject e[516041551360]
D/InputTransport: Input channel destroyed: 'ClientS',fd=84
D/SurfaceControl: release : Surface(name=Surface(name=26f5368 InputMethod)/@0xac28067 - animation-leash)/@0x8d5a51
I/SurfaceControl: nativeRelease nativeObject s[516041548224]
    nativeRelease nativeObject e[516041548224]
I/mali_egl: eglDestroySurface() in
I/mali_winsys: delete_surface() [1080x2400] return
I/mali_egl: eglDestroySurface() out
W/libEGL: EGLNativeWindowType 0x79467b3f10 disconnect Failed
D/SurfaceControl: release : Surface(name=null)/@0xf6cdbb7
I/SurfaceControl: nativeRelease nativeObject s[516041602320]
    nativeRelease nativeObject e[516041602320]
I/ViewRootImpl@541c6e9[MainActivity]: Relayout returned: old=(0,2400)8 dur=4 res=0x5 s={false 0} ch=true fn=19
I/ViewRootImpl@541c6e9[MainActivity]: stopped(true) old=false

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...