我需要创建一个超级简单的应用程序,只需创建一个可检测的蓝牙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
次检查中得到了肯定的结果,所以我不确定我能在我身边做些什么。有没有人对这个图书馆有任何麻烦?
下面的代码是示例available here的98%。我正在使用Android 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);
}
}
答案 0 :(得分:3)
您需要先检查设备的外围设备模式支持。使用此代码将有助于您
BluetoothManager btManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
BluetoothAdapter btAdapter = btManager.getAdapter();
if (btAdapter.isEnabled())
boolean isSupported = btAdapter.isMultipleAdvertisementSupported()) ;
答案 1 :(得分:0)
我知道这是一篇过时的文章,可能与它无关,但请记住打开蓝牙!这就是向我抛出错误的原因!