有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在执行延迟处理程序后停止Android服务?

我有一个类“ScanFunction.java”包含静态方法“startedscan”来扫描可编程设备。我想使用服务“BackgroundBleScanner”扫描BLE设备。我已将扫描周期设置为2000毫秒。现在,我想在延迟处理程序完成执行后停止服务

扫描功能。java

public class ScanFunction {

private static final int SCAN_PERIOD = 2000;
private static ArrayList<byte[]> byteList;
private static Handler handler;
@TargetApi(21)
private static ScanCallback getLollipopCallback() {
    ScanCallback callback = new ScanCallback() {
        @Override
        public void onScanFailed(int errorCode) {
            Log.e("Lollipop Callback", "Error Code : " + errorCode);
        }

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            byte[] beacBytes = result.getScanRecord().getBytes();
            Utilities.bytesToBeacon(beacBytes,result.getRssi()); //Function to fetch beacon UUID and store it in Application class
        }
    };
    return callback;
}

@TargetApi(21)
private static void startLollipopScanner(BluetoothAdapter bluetoothAdapter){
    final BluetoothLeScanner leScanner = bluetoothAdapter.getBluetoothLeScanner();
    final ScanCallback callback = getLollipopCallback();
    ScanSettings scanSettings = (new ScanSettings.Builder()).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
    List<ScanFilter> scanFilters=null;
    handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            leScanner.stopScan(callback);
            Utilities.sortBeaconsByRssi();
        }
    },SCAN_PERIOD);
    leScanner.startScan(scanFilters,scanSettings,callback);
}

public static void startLeScan(BluetoothAdapter bluetoothAdapter){
    //byteList.clear();
    if(Build.VERSION.SDK_INT<21){
        startJellyBeanScanner(bluetoothAdapter);
    }
    else if (Build.VERSION.SDK_INT>=21){
        startLollipopScanner(bluetoothAdapter);
    }
}
}

背景扫描程序。java

public class BackgroundBleScanner extends Service {

BluetoothAdapter mBluetoothAdapter;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    if (mBluetoothAdapter != null || mBluetoothAdapter.isEnabled()){
        ScanFunction.startLeScan(mBluetoothAdapter)
    }
    Intent i = new Intent(this,BackgroundBleScanner.class);
    PendingIntent pi = PendingIntent.getService(this,12,i,PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 9000,pi);
            return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d("ondestroy","Service Destroyed");
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

共 (0) 个答案