AltBeacon信标创建应用程序



我需要创建一个超级简单的应用程序,只需创建一个可检测的蓝牙LE信标,无需传输任何数据。我选择使用AltBeacon lybrary,因此我用他们提供的一个示例实现了该应用程序。尽管如此,该应用程序还是与java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeAdvertiser.startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback)' on a null object reference 一起崩溃我在两次null检查中都得到了阳性结果,所以我不确定我还能做些什么。有人对这个图书馆有意见吗?

下面的代码是这里可用的示例的98%。我使用的是安卓5.0。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.BeaconTransmitter;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
    BeaconTransmitter beaconTransmitter;
    Beacon beacon;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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();
        if(beacon==null)
            Toast.makeText(getApplicationContext(), "NULL beacon", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(getApplicationContext(), "OK beacon", Toast.LENGTH_LONG).show();
        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 = new BeaconTransmitter(getApplicationContext(), beaconParser);
        if(beaconTransmitter==null)
            Toast.makeText(getApplicationContext(), "NULL beacon trasmitter", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(getApplicationContext(), "OK beacon trasmitter", Toast.LENGTH_LONG).show();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
             @Override
            public void run() {
                beaconTransmitter.startAdvertising(beacon);
            }
        }, 5000);

    }
}

您需要首先检查设备的外围模式支持。使用此代码将有助于u

BluetoothManager btManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
            BluetoothAdapter btAdapter = btManager.getAdapter();
            if (btAdapter.isEnabled()) 
               boolean isSupported = btAdapter.isMultipleAdvertisementSupported()) ;

我知道这是一篇旧帖子,可能没有关联,但记得打开蓝牙!这就是我犯错误的原因!

最新更新