我需要创建一个超级简单的应用程序,它只创建一个可检测的蓝牙 LE 信标,不需要传输任何数据。我选择使用 AltBeacon 库,因此我使用他们提供的示例之一实现了该应用程序。尽管如此,应用程序还是崩溃了,因为我在执行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);
}
}