这是我的MainActivity.class
public class MainActivity extends AppCompatActivity {
public BluetoothManager bluetoothManager;
public BluetoothAdapter bluetoothAdapter;
private Button button1,button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "ble_not_supported", Toast.LENGTH_SHORT).show();
finish();
}
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(new Intent(MainActivity.this,ScanService.class));
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(new Intent(MainActivity.this,ScanService.class));
}
});
}
}
这是我的ScanService.class
public class ScanService extends Service {
public BluetoothManager mbluetoothManager;
public BluetoothAdapter mbluetoothAdapter;
public final String address1 = "88:4A:EA:76:EA:21";
public final String address2 = "60:64:05:97:5C:05";
public final String address3 = "60:64:05:97:5E:A6";
int i=0;
@Override
public void onCreate() {
super.onCreate();
mbluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mbluetoothAdapter = mbluetoothManager.getAdapter();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressWarnings("deprecation")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mbluetoothAdapter.stopLeScan(mLeScanCallback);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
mbluetoothAdapter.startLeScan(mLeScanCallback);
return START_STICKY;
}
@SuppressWarnings("deprecation")
@Override
public void onDestroy() {
mbluetoothAdapter.stopLeScan(mLeScanCallback);
super.onDestroy();
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
if (device != null && rssi != 127) {
switch (device.getAddress()) {
//==============================================================================
case address1:
if (i == 0)
Log.d("Beacon:","1");
break;
//==============================================================================
case address2:
if (i == 1) {
i = 2;
Log.d("Beacon:","2");
}
break;
//==============================================================================
case address3:
if (i == 2) {
i = 3;
Log.d("Beacon:","3");
}
break;
default: break;
}
}
}
};
}
我可以启动扫描服务但是在我的日志中它不会返回有关检测到的信标的任何信息,这意味着应用程序正在扫描但没有找到任何信标。我还有什么必须投入我的服务吗?