android 蓝牙重复扫描

移动开发 码拜 8年前 (2017-04-27) 2714次浏览
本人想在service内让蓝牙可以一直执行扫描,之前在activity内可以重复扫描,但移植到服务后就不能了问一下要怎么解决?
public class search_beacon extends Service implements LocationListener {
HashMap<String, Integer> record = new HashMap<String, Integer>();
private Long startTime;
private Handler timer = new Handler();
LocationManager locationManager;
String best_loc;
double latitude;
double longitude;
String sql;
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1234;
private Handler mHandler;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate(){
Log.i(“search_beacon”, “Enter onCreate()”);
super.onCreate();
Log.i(“search_beacon”, “Leave onCreate()”);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(“search_beacon”,”Enter onStartCommand()”);

//宣告倒數
mHandler = new Handler();
//ble
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, “BLE Not Supported”,
Toast.LENGTH_SHORT).show();
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
//gps
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//set the location provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
best_loc = locationManager.getBestProvider(criteria, true);
if (best_loc != null) {
Location loc = locationManager.getLastKnownLocation(best_loc);
showlocation(loc);
}
//計時器設定
startTime = System.currentTimeMillis();
//設定定時要執行的方法
timer.removeCallbacks(updateTimer);
//設定Delay的時間
timer.postDelayed(updateTimer, 5000);
if (mBluetoothAdapter.isEnabled()) {
if (Build.VERSION.SDK_INT >= 21) {
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
filters = new ArrayList<ScanFilter>();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
}
scanLeDevice(true);
}
return Service.START_STICKY;
}
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}, SCAN_PERIOD);
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
String device_mac;
Integer device_rssi;
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.i(“callbackType”, String.valueOf(callbackType));
Log.i(“result”, result.toString());
BluetoothDevice btDevice = result.getDevice();
//connectToDevice(btDevice);
Log.i(“jiejv”,btDevice.getAddress());
device_mac = btDevice.getAddress();
device_rssi = result.getRssi();
String check_mac=device_mac.substring(0, 11);  //第十一碼以前,不含十一
if(device_mac.equals(null) || device_rssi== null)
Log.i(“jiejv”,device_mac+”空空空”+device_rssi);
else if(check_mac.equals(“01:17:C5:57”))
{
record.put(device_mac,device_rssi);
}
//if(update_record(device_mac,device_rssi))
Log.i(“jiejv”,device_mac+”   “+device_rssi);
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.i(“ScanResult – Results”, sr.toString());
}
}
@Override
public void onScanFailed(int errorCode) {
Log.e(“Scan Failed”, “Error Code: ” + errorCode);
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {

@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(“onLeScan”, device.toString());
//connectToDevice(device);
}
});
}
};
//固定要執行的方法
private Runnable updateTimer = new Runnable() {
public void run() {
Iterator<?> it = record.entrySet().iterator();
while(it.hasNext())
{
Map.Entry me = (Map.Entry)it.next();
String mac = me.getKey().toString();
int rs = (int)me.getValue();
if(update_record(mac,rs))
{
Log.i(“timer”,mac+”  “+rs);
// record.remove(me.getKey());
}
}
record.clear();
timer.postDelayed(this, 10000);
}
};
@Override
public void onDestroy() {
Log.i(“search_beacon”,”Enter onDestroy()”);
super.onDestroy();
handler1.removeCallbacks(showTime);     //利用removeCallbacks()停止handler.post(showTime)
Log.i(“search_beacon”,”Leave onDestroy()”);
}
}

解决方案

50

看你的代码应该是做BLE相关的,可以参考下http://blog.csdn.net/xiaoyaoyou1212/article/details/52346904,这个是使用介绍,在GIthub上有源码及demo演示,已通过实际项目验证。针对你这种情况,只需要注册一个服务,在服务中操作扫描等功能就行,希望对你有所帮助!

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明android 蓝牙重复扫描
喜欢 (0)
[1034331897@qq.com]
分享 (0)