Autore Topic: Estimote SDK, avviare e fermare il ranging  (Letto 524 volte)

Offline Elmvor

  • Utente normale
  • ***
  • Post: 166
  • Respect: 0
    • Mostra profilo
  • Sistema operativo:
    Ubuntu 14.04, Windows 8.1
Estimote SDK, avviare e fermare il ranging
« il: 02 Aprile 2015, 16:53:52 CEST »
0
Salve. Non so se qualcuno conosce questo SDK. Ecco il link, così almeno avete un'idea di cosa si tratta: http://estimote.com/api/

Comunque in breve l'app che sto scrivendo capta e visualizza in un ListFragment i beacon captati, per ora in automatico. Intendo dire che appena l'app viene avviata, il ranging inizia e nel caso vengono visualizzati i beacon trovati.

Ora sto cercando di farlo manualmente tramite due tasti posti sul menù. Un tasto avvia la scansione, l'altro la ferma. Quel che però accade è che l'app si chiude in entrambi i casi, senza comunque vedere alcun errore nel log.

Questo è il codice:

Codice: [Seleziona]
public class BeaconsDetector extends Activity {

    /** defines the region to scan (in this case, scan all the possible beacons */
    private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region("rid", null, null, null);

    /** constant value for the bluetooth activation request */
    private static final int REQUEST_ENABLE_BT = 1234;

    /** constant string for used by the Log */
    private static final String TAG = BeaconsDetector.class.getSimpleName();

    /** class that manage all the stuff about the beacons */
    private BeaconManager beaconManager = new BeaconManager(this);

    /** indicates whether the activity is scanning for beacons */
    private boolean ranging;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /* Apps can use the startRanging method of the BeaconManager class to determine relative proximity of beacons in the region and can be updated when this distance changes.
           Ranging updates come every second to listeners registered with the setRangingListener method of the BeaconManager class.
           Ranging updates contain a list of currently found beacons. If a beacon goes out of range it will not be presented on this list.
           Ranging is designed to be used for apps running in the foreground.
         */
        /** establishes what happens when some beacons is detected */
        beaconManager.setRangingListener(new BeaconManager.RangingListener() {
            @Override
            public void onBeaconsDiscovered(Region region, List<Beacon> beacons) {
                // aggiorna il fragment
                final DiscoveredBeacons fragment = (DiscoveredBeacons) getFragmentManager()
                        .findFragmentById(R.id.frag_list);
                if (!beacons.isEmpty())
                    fragment.updateList(beacons);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            // start the scan if it is not started yet
            case R.id.start_scan:
                if(!ranging) {
                    startRanging();
                } else {
                    Toast.makeText(this, "Already scanning...", Toast.LENGTH_SHORT).show();
                }
            // stop the scan if it is started
            case R.id.stop_scan:
                if(ranging) {
                    stopScan();
                } else {
                    Toast.makeText(this, "Already stopped...", Toast.LENGTH_SHORT).show();
                }
            // terminate the app
            case R.id.quit_app:
                finish();

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /** starts the ranging */
    private void startRanging() {
        connectToService();
    }

    /** stop the ranging and disconnect */
    private void stopScan() {
        try {
            beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS_REGION);
            ranging = false;
        } catch (RemoteException e) {
            Log.e(TAG, "Cannot stop the ranging", e);
        }
    }

    public void onStart() {
        super.onStart();

        // Check if device supports Bluetooth Low Energy.
        if (!beaconManager.hasBluetooth()) {
            Toast.makeText(this, "Device does not have Bluetooth Low Energy", Toast.LENGTH_LONG).show();
            return;
        }
        // If Bluetooth is not enabled, let user enable it.
        if (!beaconManager.isBluetoothEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            connectToService();
        }
    }

    private void connectToService() {
        // connection to the service
        beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
            @Override
            public void onServiceReady() {
                try {
                    /** Starts ranging given range. Ranging results will be delivered to listener registered via setRangingListener(RangingListener).
                     *  If given region is already ranged, this is no-op.
                     */
                    beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
                    ranging = true;
                } catch (RemoteException e) {
                    Log.e(TAG, "Cannot start ranging", e);
                }
            }
        });
        Log.d(TAG, "Start Ranging - Ranging: " + ranging);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                connectToService();
            } else {
                Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG).show();
                getActionBar().setSubtitle("Bluetooth not enabled");
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void onStop() {
        super.onStop();
        try {
            beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS_REGION);
            ranging = false;
        } catch (RemoteException e) {
            Log.e(TAG, "Cannot stop but it does not matter now", e);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        beaconManager.disconnect();
    }
}

Risolto, ci vuole un return true per ogni case dello switch...
« Ultima modifica: 02 Aprile 2015, 18:43:58 CEST da Elmvor »