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

<uses-sdk
    android:minSdkVersion="18"
    android:targetSdkVersion="18" />
     <uses-permission android:name="android.permission.BLUETOOTH"/>
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

检查是否进入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<Beacon> 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 
    android:name="com.example.MyApplicationName"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <!-- Note:  the singleInstance below is important to keep two copies of your activity from getting launched on automatic startup -->
    <activity
        android:launchMode="singleInstance"  
        android:name="com.example.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
    <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
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应用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,088评论 2 44
  • 食材:土豆,宽粉,木耳,肉(鸡胸肉/猪肉),豆腐,青椒,大白菜,西红柿。 调料:葱姜蒜,辣椒,花椒,孜然。油,盐,...
    咸鱼快跑阅读 200评论 0 0
  • 你是否也和我一样 会十分珍惜夜里的每一个梦 这梦有时只是一个片段 有时竟是完整的故事 有时知道自己在做梦 有时不知...
    有海的森林阅读 178评论 1 4
  • 咳咳咳,是的又是我,那个前段时间写了国外十佳的那位(众:Who cares?~) 以下为国内专辑部分,今年国内专辑...
    披着马甲的猪阅读 491评论 0 0