Как я могу искать маяк - PullRequest
0 голосов
/ 08 мая 2018

Я не вижу маяков в этих версиях Android (Android 7.0 API 24, Android 6.0.1 API 23). Я вижу сообщение «Не удалось найти оболочку обратного вызова», однако Android 4.4.4, API 19 работает отлично

это мой код: открытый класс Tab3Helper расширяет Fragment реализует BeaconConsumer { // Относительная компоновка RelativeLayout rl; // Recycler View частный RecyclerView rv; частный RecyclerView.LayoutManager layoutManager; закрытый адаптер RecyclerView.Adapter; // Beacon Manager частный BeaconManager beaconManager; // Индикатор частный ProgressBar pb; // новый открытый статический окончательный идентификатор MY_MATCHING_IDENTIFIER = Identifier.fromInt (0x8b9c); //конец @Override public void onCreate (BundlevedInstanceState) { super.onCreate (saveInstanceState);

    //getting beaconManager instance (object) for Main Activity class
    beaconManager = BeaconManager.getInstanceForApplication (getActivity ( ));

    // To detect proprietary beacons, you must add a line like below corresponding to your beacon
    // type.  Do a web search for "setBeaconLayout" to get the proper expression.
    beaconManager.getBeaconParsers ( ).add (new BeaconParser ( ).
            setBeaconLayout ("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));

    //Binding MainActivity to the BeaconService.
            beaconManager.bind (this);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate (R.layout.tab3helper, container, false);

    // Intializing the Layout

    //Relative Layout
    rl = v.findViewById (R.id.Relative_One);

    // Recycler View
    rv = v.findViewById (R.id.search_recycler);

    //Progress Bar
    // pb = v.findViewById(R.id.pb);
    return v;
}


public void onBeaconServiceConnect() {
    final Region region = new  Region("myBeaons",null, null, null);
    beaconManager.addMonitorNotifier (new MonitorNotifier ( ) {

        public void didEnterRegion(Region region) {
            try {
                // Log.d(TAG, "didEnterRegion");
                beaconManager.startRangingBeaconsInRegion (region);
            } catch (RemoteException e) {
                e.printStackTrace ( );
            }
        }


        public void didExitRegion(Region region) {
            try {
                //Log.d(TAG, "didExitRegion");
                beaconManager.stopRangingBeaconsInRegion (region);
            } catch (RemoteException e) {
                e.printStackTrace ( );
            }
        }




        public void didDetermineStateForRegion(int state, Region region) {
            System.out.println( "I have just switched from seeing/not seeing beacons: "+state);
        }
    });

    beaconManager.addRangeNotifier (new RangeNotifier ( ) {

        public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
          //  Log.d(TAG, "distance: " + oneBeacon.getDistance() + " id:" + oneBeacon.getId1() + "/" + oneBeacon.getId2() + "/" + oneBeacon.getId3());
            /*
            for (Beacon oneBeacon : beacons) {
                System.out.println ("Major value =" +oneBeacon.getId2 ()+ "size =" +beacons.size () + "*");
            }
            */
            if(beacons.size()>0){
               //System.out.print("**"+beacons.size()+"**");
                try{
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            // Make ProgressBar Invisible
                            //pb.setVisibility(View.INVISIBLE);

                            // Make Relative Layout to be Gone
                            rl.setVisibility(View.GONE);

                            //Make RecyclerView to be visible
                            rv.setVisibility(View.VISIBLE);

                            // Setting up the layout manager to be linear
                            layoutManager = new LinearLayoutManager(getActivity());
                            rv.setLayoutManager(layoutManager);
                        }
                    });
                }
                catch(Exception e){

                }
                final ArrayList<ArrayList<String>> arrayList = new ArrayList<ArrayList<String>>();

                // Iterating through all Beacons from Collection of Beacons
                for (Beacon b:beacons) {
                    //new

                        String receivedString = null;

                       // byte[] bytes = b.getId2().toByteArray();
                       //byte[] bytes = b.getId2().toByteArray();
                                byte[] bytes = b.getId1().toByteArray();





                        receivedString = null;

                        try {
                            receivedString = new String(bytes, 0, bytes.length, "ASCII");


                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                    String uuid = receivedString;

                    //end new
                    //UUID
                   // String uuid = String.valueOf(b.getId1());

                    //Major
                    String major = String.valueOf(b.getId2());

                    //Minor
                    String minor = String.valueOf(b.getId3());
                    // test

                    //Distance
                    double distance1 = b.getDistance();
                    String distance = String.valueOf(Math.round(distance1 * 100.0) / 100.0);
                    //Name
                    String nameUser = b.getBluetoothName();


                    ArrayList<String> arr = new ArrayList<String>();
                    arr.add(uuid);
                    arr.add(major);
                    arr.add(minor);
                    arr.add(distance + " meters");
                    arr.add(nameUser);
                    arrayList.add(arr);
                    //System.out.print("**"+b.getId1()+"**");
                    //System.out.print("**"+arrayList.size()+"**");
                }

                try {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            // Setting Up the Adapter for Recycler View
                            adapter = new RecyclerAdapter(arrayList);
                            rv.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                        }
                    });
                }catch(Exception e){

                }




                //fin

            }
        }

    });

    try {
        beaconManager.startMonitoringBeaconsInRegion (region);
    } catch (RemoteException e) {
        e.printStackTrace ( );
    }

}

1 Ответ

0 голосов
/ 08 мая 2018

Android 6.0+ добавляет несколько новых ограничений на сканирование маяков Bluetooth:

  1. Местоположение должно быть включено в настройках. Если он выключен, маяки не будут обнаружены.
  2. Приложения должны получать разрешение на местоположение от пользователя во время выполнения. Если они этого не делают, сканирование завершается сбоем без вывода сообщений.

Для пункта 2 выше следуйте инструкциям, подобным this

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