Android Beacon Library的使用

IBeacon的简介

Beacon是苹果公司2013年9月发布的移动设备用OS(iOS7)上配备的新功能。其工作方式是,配备有 低功耗蓝牙(BLE)通信功能的设备使用BLE技术向周围发送自己特有的ID,接收到该ID的应用软件会根据该ID采取一些行动。由于IBeacon是苹果发布的,所以会有相应的工具库;但是android是在4.3系统及以后才支持低功耗蓝牙,也没有相关的IBeacon库,只能用android BLE的基本操作,使用相对麻烦,所以才出现了Android Beacon Library,详细介绍,Github。

环境配置

Step 1. 配置你的项目build.gradle文件

repositories {
 jcenter()
}   

dependencies {
 compile 'org.altbeacon:android-beacon-library:2+'
}

Step 2.在AndroidManifest.xml中添加权限,android6.0及以上动态申请权限Manifest.permission.ACCESS_COARSE_LOCATION


     
     

检查是否进入Beacon区域

当我们走进或走出一个beacon广播区域时,我们会收到相应回调,下面将打印相应的log。

public class MonitoringActivity extends Activity implements BeaconConsumer {
protected static final String TAG = "MonitoringActivity";
private BeaconManager beaconManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ranging);
            beaconManager = BeaconManager.getInstanceForApplication(this);
    // 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"));
    beaconManager.bind(this);
}
@Override 
protected void onDestroy() {
    super.onDestroy();
    beaconManager.unbind(this);
}
@Override
public void onBeaconServiceConnect() {
    beaconManager.addMonitorNotifier(new MonitorNotifier() {
    @Override
    public void didEnterRegion(Region region) {
        Log.i(TAG, "I just saw an beacon for the first time!");        
    }

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

    @Override
        public void didDetermineStateForRegion(int state, Region region) {
        Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);        
        }
    });
    
    try {
        beaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
    } catch (RemoteException e) {    }
}
}

获取附近的Beacon设备信息

我们可以在didRangeBeaconsInRegion回调中获取到Beacon集合,然后遍历可以获取到每个Beacon的基本信息如major,minor,UUID,距离等。

public class RangingActivity extends Activity implements BeaconConsumer {
protected static final String TAG = "RangingActivity";
private BeaconManager beaconManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ranging);
    beaconManager = BeaconManager.getInstanceForApplication(this);
    // 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"));
    beaconManager.bind(this);
}
@Override 
protected void onDestroy() {
    super.onDestroy();
    beaconManager.unbind(this);
}
@Override
public void onBeaconServiceConnect() {
    beaconManager.addRangeNotifier(new RangeNotifier() {
        @Override 
        public void didRangeBeaconsInRegion(Collection beacons, Region region) {
            if (beacons.size() > 0) {
                Log.i(TAG, "The first beacon I see is about "+beacons.iterator().next().getDistance()+" meters away.");        
            }
        }
    });
    
    try {
        beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
    } catch (RemoteException e) {    }
}
}

运行于后台

后台启动的activity的launchMode="singleInstance"


    
    
        
    
            
        
    

Application class
public class MyApplicationName extends Application implements BootstrapNotifier {
private static final String TAG = ".MyApplicationName";
private RegionBootstrap regionBootstrap;

@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "App started up");
    BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
    // 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"));

    // wake up the app when any beacon is seen (you can specify specific id filers in the parameters below)
    Region region = new Region("com.example.myapp.boostrapRegion", null, null, null);
    regionBootstrap = new RegionBootstrap(this, region);
}

@Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
    // Don't care
}

@Override
public void didEnterRegion(Region arg0) {
    Log.d(TAG, "Got a didEnterRegion call");
    // This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
    // if you want the Activity to launch every single time beacons come into view, remove this call.  
    regionBootstrap.disable();
    Intent intent = new Intent(this, MainActivity.class);
    // IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
    // created when a user launches the activity manually and it gets launched from here.
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.startActivity(intent);
}

@Override
public void didExitRegion(Region arg0) {
    // Don't care
}        
}

把手机变成一个Beacon发射器(必须SDK21+,android5.0)

Beacon beacon = new Beacon.Builder()
    .setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
    .setId2("1")
    .setId3("2")
    .setManufacturer(0x0118)
    .setTxPower(-59)
    .setDataFields(Arrays.asList(new Long[] {0l}))
    .build();
BeaconParser beaconParser = new BeaconParser()
    .setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(getApplicationContext(), beaconParser); 
beaconTransmitter.startAdvertising(beacon);

节省电量

public class MyApplication extends Application implements BootstrapNotifier {
private BackgroundPowerSaver backgroundPowerSaver;

public void onCreate() {
    super.onCreate();
    // Simply constructing this class and holding a reference to it in your custom Application class
    // enables auto battery saving of about 60%
    backgroundPowerSaver = new BackgroundPowerSaver(this);
}
}

以上就是Android Beacon Library的使用,通过它我们可以快速地在android手机上开发Beacon应用。

你可能感兴趣的:(Android Beacon Library的使用)