Android-приложение не сканирует маяки после первого запуска - PullRequest
0 голосов
/ 20 июня 2019

Я пытаюсь создать приложение, в котором определяется сила ближайшего маяка (по силе сигнала) и должен вызываться соответствующий API (с идентификатором маяка в качестве параметра).Приложение запрашивает местоположение в первый раз и работает очень хорошо (определяет ближайший маяк).Но после того, как я закрою приложение и снова открою его, идентификатор маяка будет всегда пустым (переменная string2 устанавливается с идентификатором маяка).Почему он запускается в первый раз, а не в следующий раз?

Всякий раз, когда я очищаю данные приложения, приложение запрашивает местоположение и работает нормально.Я снова трижды закодировал весь сегмент, и все же столкнулся с той же проблемой.

Я попытался отследить поток с помощью операторов журнала.Я заметил, что метод onBeaconServiceConnect () не выполняется во второй раз (если данные приложения не очищены).

AsyncTask:

public class Navigate extends AsyncTask<String, String, String> {

        protected String doInBackground(String... strings) {
            //REST Query
            String cs, ps = null;

    //Here bid is a field and it will be set to Beacon ID of the nearest beacon.

                while (!bid.equals(strings[1])) {
                    try {
                        imageURL=callAPI("bid1","bid3");
                         Log.e("BeaconID", bid); //The default value of bid will be printed and not the beacon ID.


                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }



            Log.e("Debug", "Step3");

            return "none";
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }


        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);

            Toast.makeText(getApplicationContext(), "onProgressUpdate", Toast.LENGTH_SHORT).show();
            mNetworkImageView = (NetworkImageView) findViewById(R.id.mapImage);
            mImageLoader = CustomVolleyRequestQueue.getInstance(getApplicationContext()).getImageLoader();
            mImageLoader.get(values[0], ImageLoader.getImageListener(mNetworkImageView, R.mipmap.ic_launcher_round, android.R.drawable.ic_menu_report_image));
            Log.e("Image Published", values[0]);
            mNetworkImageView.setImageUrl(values[0], mImageLoader);

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressDialog.dismiss();
            tv.setText(s);

        }
    }

OnBeaconServiceConnect: -

public void onBeaconServiceConnect() {

        //Constructing a new Region object to be used for Ranging or Monitoring
        region = new Region("myBeaons", Identifier.parse("23542266-18D1-4FE4-B4A1-23F8195B9D39"), null, null);

        //Specifies a class that should be called each time the BeaconService sees or stops seeing a Region of beacons.
        beaconManager.addMonitorNotifier(new MonitorNotifier() {

            /*
                This override method is runned when some beacon will come under the range of device.
            */

            @Override
            public void didEnterRegion(Region region) {
                System.out.println("ENTER ------------------->");
                try {

                    //Tells the BeaconService to start looking for beacons that match the passed Region object
                    // , and providing updates on the estimated mDistance every seconds while beacons in the Region
                    // are visible.
                    beaconManager.startRangingBeaconsInRegion(region);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Log.e("Debug", "Step10");
            }


            /*
                 This override method is runned when beacon that comes in the range of device
                 ,now been exited from the range of device.
             */
            @Override
            public void didExitRegion(Region region) {
                System.out.println("EXIT----------------------->");
                try {

                    //Tells the BeaconService to stop looking for beacons
                    // that match the passed Region object and providing mDistance
                    // information for them.
                    beaconManager.stopRangingBeaconsInRegion(region);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Log.e("Debug", "Step11");
            }


            /*
                 This override method will Determine the state for the device , whether device is in range
               of beacon or not , if yes then i = 1 and if no then i = 0
            */
            @Override
            public void didDetermineStateForRegion(int state, Region region) {
                System.out.println("I have just switched from seeing/not seeing beacons: " + state);
            }
        });


        //Specifies a class that should be called each time the BeaconService gets ranging data,
        // which is nominally once per second when beacons are detected.
        beaconManager.addRangeNotifier(new RangeNotifier() {

            /*
               This Override method tells us all the collections of beacons and their details that
               are detected within the range by device
             */
            @Override
            public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {

                // Checking if the Beacon inside the collection (ex. list) is there or not

                // if Beacon is detected then size of collection is > 0

                if (beacons.size() > 0) {

                    final ArrayList<ArrayList<String>> arrayList = new ArrayList<ArrayList<String>>();
                    BeaconManager.setRssiFilterImplClass(ArmaRssiFilter.class);
                    // Iterating through all Beacons from Collection of Beacons
                    ArrayList<Integer> arr = new ArrayList<Integer>();
                    int count = 0;
                    for (Beacon b : beacons) {
                        //RSSI
                        count += 1;
                        System.out.println(b.getBluetoothAddress()+" : "+b.getBluetoothName());
                        System.out.println("Count : " + count);
                        Integer rssi = Integer.valueOf(b.getRssi());
                        arr.add(rssi);

                        Integer maxRssi = Collections.max(arr);
                        for(Beacon b1 : beacons){

                            if(b1.getRssi() == maxRssi)
                            {
                                start = b1.getId1().toString();
                                maxid = start;
                                Log.e("Debug", "Step12");
                                System.out.println("uuid :"+func());
                            }
                        }
                    }
                }
            }
        });
        try {

            //Tells the BeaconService to start looking for beacons that match the passed Region object.
            beaconManager.startMonitoringBeaconsInRegion(region);
        } catch (RemoteException e) {
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //Unbinds an Android Activity or Service to the BeaconService to avoid leak.
        beaconManager.unbind(this);
        finish();
    }

Ставка устанавливается с первого хода.Когда я выхожу из приложения и снова открываю его, ставка не изменится.Я должен очистить данные приложения и заново запустить его для правильной работы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...