Android Beacon Library的使用

IBeacon的簡介

Beacon是蘋果公司2013年9月發(fā)布的移動設(shè)備用OS(iOS7)上配備的新功能狮荔。其工作方式是蜓竹,配備有 低功耗藍牙(BLE)通信功能的設(shè)備使用BLE技術(shù)向周圍發(fā)送自己特有的ID,接收到該ID的應(yīng)用軟件會根據(jù)該ID采取一些行動不撑。由于IBeacon是蘋果發(fā)布的凫碌,所以會有相應(yīng)的工具庫;但是android是在4.3系統(tǒng)及以后才支持低功耗藍牙探遵,也沒有相關(guān)的IBeacon庫,只能用android BLE的基本操作妓柜,使用相對麻煩箱季,所以才出現(xiàn)了Android Beacon Library,詳細介紹,Github

環(huán)境配置

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

repositories {
 jcenter()
}   

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

Step 2.在AndroidManifest.xml中添加權(quán)限棍掐,android6.0及以上動態(tài)申請權(quán)限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區(qū)域

當我們走進或走出一個beacon廣播區(qū)域時规哪,我們會收到相應(yīng)回調(diào),下面將打印相應(yīng)的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設(shè)備信息

我們可以在didRangeBeaconsInRegion回調(diào)中獲取到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發(fā)射器(必須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);

節(jié)省電量

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手機上開發(fā)Beacon應(yīng)用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末杜恰,一起剝皮案震驚了整個濱河市获诈,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌心褐,老刑警劉巖舔涎,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異逗爹,居然都是意外死亡亡嫌,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來挟冠,“玉大人于购,你說我怎么就攤上這事≈荆” “怎么了肋僧?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長控淡。 經(jīng)常有香客問我嫌吠,道長,這世上最難降的妖魔是什么逸寓? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任居兆,我火速辦了婚禮,結(jié)果婚禮上竹伸,老公的妹妹穿的比我還像新娘泥栖。我一直安慰自己,他們只是感情好勋篓,可當我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布吧享。 她就那樣靜靜地躺著,像睡著了一般譬嚣。 火紅的嫁衣襯著肌膚如雪钢颂。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天拜银,我揣著相機與錄音殊鞭,去河邊找鬼。 笑死尼桶,一個胖子當著我的面吹牛操灿,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播泵督,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼趾盐,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了小腊?” 一聲冷哼從身側(cè)響起救鲤,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎秩冈,沒想到半個月后本缠,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡入问,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年搓茬,在試婚紗的時候發(fā)現(xiàn)自己被綠了犹赖。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡卷仑,死狀恐怖峻村,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情锡凝,我是刑警寧澤粘昨,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站窜锯,受9級特大地震影響张肾,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜锚扎,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一吞瞪、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧驾孔,春花似錦芍秆、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至对碌,卻和暖如春荆虱,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背朽们。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工怀读, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人骑脱。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓菜枷,卻偏偏與公主長得像,于是被迫代替她去往敵國和親惜姐。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,167評論 25 707
  • afinalAfinal是一個android的ioc椿息,orm框架 https://github.com/yangf...
    passiontim閱讀 15,434評論 2 45
  • 食材:土豆歹袁,寬粉,木耳寝优,肉(雞胸肉/豬肉)条舔,豆腐,青椒乏矾,大白菜孟抗,西紅柿迁杨。 調(diào)料:蔥姜蒜,辣椒凄硼,花椒铅协,孜然。油摊沉,鹽狐史,...
    咸魚快跑閱讀 219評論 0 0
  • 你是否也和我一樣 會十分珍惜夜里的每一個夢 這夢有時只是一個片段 有時竟是完整的故事 有時知道自己在做夢 有時不知...
    有海的森林閱讀 201評論 1 4
  • 咳咳咳,是的又是我说墨,那個前段時間寫了國外十佳的那位(眾:Who cares?~) 以下為國內(nèi)專輯部分骏全,今年國內(nèi)專輯...
    披著馬甲的豬閱讀 536評論 0 0