Android app退至后台, btAdapter.startLeScan(leScanCallback);停止了,怎么让他一直扫描。。。

8023灬 发布于 2016/11/04 11:31
阅读 361
收藏 0
public class IbeaconService extends Service {  public static final String TAG = "IbeaconService";  private BluetoothManager btManager;  private BluetoothAdapter btAdapter;  private Handler scanHandler = new Handler();  private int scan_interval_ms = 5000;  private boolean isScanning = false;  private boolean isFirst = false;  private List<BeaconModel> list=new ArrayList<BeaconModel>();  private List<BeaconModel> newList=new ArrayList<BeaconModel>();  private Map<String,BeaconModel> beaconMap=new HashMap<>();  @Nullable  @Override  public IBinder onBind(Intent intent) {   return null;  }    @Override  public int onStartCommand(Intent intent, int flags, int startId) {  // TODO Auto-generated method stub  Log.v("TrafficService","startCommand"); //        scanHandler.post(scanRunnable);   flags = START_STICKY;  return super.onStartCommand(intent, flags, startId);  // return START_REDELIVER_INTENT;  }    //创建服务时调用  @Override  public void onCreate() {  super.onCreate();  Log.d(TAG, "onCreate");  btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);  btAdapter = btManager.getAdapter(); //        setDiscoverableTimeout(30000);  btAdapter.startLeScan(leScanCallback);  Intent intent=new Intent(IbeaconService.this,IbeaconSubmitService.class);  startService(intent);  }  private Runnable scanRunnable = new Runnable()  {  @Override  public void run() {   if (isScanning)  {  if (btAdapter != null)  {  btAdapter.stopLeScan(leScanCallback);  Log.d("8023",btAdapter.startDiscovery()+"");  }  }  else  {  if (btAdapter != null)  {  Log.d("8023",btAdapter.startDiscovery()+""); //                    btAdapter.getBluetoothLeScanner().startScan(new ScanCallback() { //                        @Override //                        public void onScanResult(int callbackType, ScanResult result) { //                            Log.d("8023", result+" result"); //                            super.onScanResult(callbackType, result); //                        } //                    });  btAdapter.startLeScan(leScanCallback);   }  }   isScanning = !isScanning;   scanHandler.postDelayed(this, scan_interval_ms);  }  };   private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {  @Override  public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {  int rang = rssi;  int startByte = 2;  boolean patternFound = false;  while (startByte <= 5) {  if (((int) scanRecord[startByte + 2] & 0xff) == 0x02 && //Identifies an iBeacon  ((int) scanRecord[startByte + 3] & 0xff) == 0x15) { //Identifies correct data length  patternFound = true;  break;  }  startByte++;  }  if (patternFound) {  //Convert to hex String  byte[] uuidBytes = new byte[16];  System.arraycopy(scanRecord, startByte + 4, uuidBytes, 0, 16);  String hexString = bytesToHex(uuidBytes);   //UUID detection  String uuid = hexString.substring(0, 8) + "-" +  hexString.substring(8, 12) + "-" +  hexString.substring(12, 16) + "-" +  hexString.substring(16, 20) + "-" +  hexString.substring(20, 32);   // major  final int major = (scanRecord[startByte + 20] & 0xff) * 0x100 + (scanRecord[startByte + 21] & 0xff);   // minor  final int minor = (scanRecord[startByte + 22] & 0xff) * 0x100 + (scanRecord[startByte + 23] & 0xff);   BeaconModel model = new BeaconModel();  Log.i(TAG, "UUID: " + uuid + "\\nmajor: " + major + "\\nminor" + minor + "rang+:" + rang + "txPower" + (int) scanRecord[29]);   if (rang == 0) {   }  int txPower = (int) scanRecord[29];  Log.d(TAG, "calculating accuracy based on rssi of " + rssi);  double accuracy;  double ratio = rssi * 1.0 / txPower;  if (ratio < 1.0) {  accuracy = Math.pow(ratio, 10);  Log.d(TAG, " accuracy: +~1:" + accuracy);  } else {  accuracy = (0.89976) * Math.pow(ratio, 7.7095) + 0.111;    Log.d(TAG, " avg rssi: " + rssi + " accuracy: ~2:" + accuracy);  }  if (accuracy<5){  model.setRang("very_near");  }else if(accuracy<10){  model.setRang("near");  }else if(accuracy>10){  model.setRang("far");  }   Date date = new Date();    model.setUuid(uuid);  model.setMajor(major + "");  model.setMinor(minor + "");  model.setTime(date);  Wyal.getInstance().getUser().AddBeacon(model);   }}  };        /**  * bytesToHex method  */  static final char[] hexArray = "0123456789ABCDEF".toCharArray();  private static String bytesToHex(byte[] bytes)  {  char[] hexChars = new char[bytes.length * 2];  for ( int j = 0; j < bytes.length; j++ )  {  int v = bytes[j] & 0xFF;  hexChars[j * 2] = hexArray[v >>> 4];  hexChars[j * 2 + 1] = hexArray[v & 0x0F];  }  return new String(hexChars);  }  private void addBeacon(BeaconModel model) {  List<String> errorMajor = new ArrayList<>();  Date nowTime = new Date();  for (Map.Entry<String, BeaconModel> item : beaconMap.entrySet()) {  if (nowTime.getTime() - item.getValue().getTime().getTime() > 2700000) {  errorMajor.add(item.getKey());  }  }  for (String list : errorMajor) {  beaconMap.remove(list);  }  beaconMap.put(model.getMajor(), model);  for (Map.Entry<String, BeaconModel> item : beaconMap.entrySet()){  Log.d(TAG, " item.vlues " + item.getValue().getMajor()+ " getTime(): " + item.getValue().getTime());  }  } //    //服务执行的操作 //    @Override //    public int onStartCommand(Intent intent, int flags, int startId) { //        Log.d(TAG, "onStartCommand"); //        scanHandler.post(scanRunnable); //        return super.onStartCommand(intent, flags, startId); //    }   //销毁服务时调用  @Override  public void onDestroy() {  super.onDestroy();  Log.d(TAG, "onDestroy");  Intent localIntent = new Intent();  localIntent.setClass(this, IbeaconService.class); //銷毀時重新啟動Service  this.startService(localIntent);    }  public void setDiscoverableTimeout(int timeout) {  BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();  try {  Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);  setDiscoverableTimeout.setAccessible(true);  Method setScanMode =BluetoothAdapter.class.getMethod("setScanMode", int.class,int.class);  setScanMode.setAccessible(true);   setDiscoverableTimeout.invoke(adapter, timeout);  setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,timeout);  } catch (Exception e) {  e.printStackTrace();  }  }  public void closeDiscoverableTimeout() {  BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();  try {  Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);  setDiscoverableTimeout.setAccessible(true);  Method setScanMode =BluetoothAdapter.class.getMethod("setScanMode", int.class,int.class);  setScanMode.setAccessible(true);   setDiscoverableTimeout.invoke(adapter, 1);  setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE,1);  } catch (Exception e) {  e.printStackTrace();  }  }  
加载中
返回顶部
顶部