Android Beacon Library的使用

IBeacon的簡介

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

檢查是否進(jìn)入Beacon區(qū)域

當(dāng)我們走進(jìn)或走出一個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) {    }
}
}

運(yùn)行于后臺

后臺啟動的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
}        
}

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,733評論 25 709
  • afinalAfinal是一個android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,835評論 2 45
  • 食材:土豆,寬粉,木耳,肉(雞胸肉/豬肉),豆腐,青椒,大白菜,西紅柿。 調(diào)料:蔥姜蒜,辣椒,花椒,孜然。油,鹽,...
    咸魚快跑閱讀 267評論 0 0
  • 你是否也和我一樣 會十分珍惜夜里的每一個夢 這夢有時只是一個片段 有時竟是完整的故事 有時知道自己在做夢 有時不知...
    有海的森林閱讀 240評論 1 4
  • 咳咳咳,是的又是我,那個前段時間寫了國外十佳的那位(眾:Who cares?~) 以下為國內(nèi)專輯部分,今年國內(nèi)專輯...
    披著馬甲的豬閱讀 610評論 0 0

友情鏈接更多精彩內(nèi)容