How to detect iBeacon in Android?

2019-06-14 05:20发布

问题:

It is the first time I work with iBeacon. So can you tell me how to detect it(give me some code example). Thanks very much. It is very important to me.

回答1:

The open source Android iBeacon Library will allow you to do this.

Here is a basic code sample:

public class MonitoringActivity extends Activity implements IBeaconConsumer {
  protected static final String TAG = "RangingActivity";
  private IBeaconManager iBeaconManager = IBeaconManager.getInstanceForApplication(this);

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ranging);
    iBeaconManager.bind(this);
  }
  @Override 
  protected void onDestroy() {
    super.onDestroy();
    iBeaconManager.unBind(this);
  }
  @Override
  public void onIBeaconServiceConnect() {
    iBeaconManager.setMonitorNotifier(new MonitorNotifier() {
    @Override
    public void didEnterRegion(Region region) {
      Log.i(TAG, "I just saw an iBeacon for the firt time!");       
    }

    @Override
    public void didExitRegion(Region region) {
      Log.i(TAG, "I no longer see an iBeacon");
    }

    @Override
    public void didDetermineStateForRegion(int state, Region region) {
        Log.i(TAG, "I have just switched from seeing/not seeing iBeacons: "+state);     
    }
    });

    try {
        iBeaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
    } catch (RemoteException e) {   }
  }

}

Full disclosure: I am Chief Engineer for Radius Networks and author of the library.