服务和线程

时间:2018-02-08 16:29:18

标签: java android multithreading service

我想构建一个启动服务的应用程序。如果APP已关闭,此服务也可以运行。

所以我在我的BLEActivity.java的OnCreate方法上构建这段代码:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble);
        startService(new Intent(this, BlePowerService.class));
}

现在我希望这个服务每隔5分钟启动一次,如果APP关闭的话。

正确的方法是创建Thread到BlePowerService?

所以我建立了这个:

public class BlePowerService extends Service {
    public DbLayer db;
    Setting settingApp;
    List<ScanFilter> filters;
    String[] stringSequence = new String[] {CHARACTERISTIC_FORZA_STRING};
    BluetoothAdapter mBluetoothAdapter;
    BluetoothGatt mGatt;
    BluetoothDevice currDevice;
    static final long SCAN_PERIOD = 1000;
    BluetoothLeScanner mLEScanner;
    Handler mHandler;
    int ReadQueueIndex;
    List<BluetoothGattCharacteristic> ReadQueue;
    ScanSettings settings;
    int id = 1000;
    boolean valore;
    //String UuID = "f0001132-0451-4000-b000-000000000000";
    String LOG_CODE = "NOTIFSRV";
    int NOTIFICATION_GREEN = 1;
    int NOTIFICATION_RED = 2;
    int START_HOUR = 7;
    int RANGE_HOURS_WEIGHT = 13;
    int START_NOTIFY = 9;
    int END_NOTIFY = 21;
    public static String PAR_NOTIFICATION_EXERCISEID = "parNotificationExerciseId";
    String NEW_ACTIVITY_START = "NAS";
    String OPEN_ACTIVITY_START = "OAS";

    public BlePowerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler();

        Context sharedContext = null;
        try {
            sharedContext = this.createPackageContext(
                    "com.eresult.diabesitycare.devicesensor",
                    Context.CONTEXT_INCLUDE_CODE);
            if (sharedContext == null) {
                return;
            }
            db=new DbLayer(sharedContext);
            db.open();


        } catch (Exception e) {
            String error = e.getMessage();
          //  Log.d(LOG_CODE,"DB error : " + error);
            return;
        }

    }



    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            //RECUPERO LE IMPOSTAZIONI SETTATE DALL'UTENTE
            settingApp = db.fetchSetting();
            mTimer = new Timer();
            mTimer.schedule(timerTask, 2500, 1 * 60 * 1000);
        } catch (Exception e) {
           // Log.e("POWER_SERVICE", e.getMessage());
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private Timer mTimer;

    TimerTask timerTask = new TimerTask() {

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void run() {
            //LEGGO TUTTI I DATI DAL SENSORE FINCHE CI SONO VALORI
            valore = true;
            int conta = 0;
            while(valore){
                conta++;
                Log.v("CICLO WHILE", conta+"");
                if (currDevice != null) {
                    GattClientCallback gattClientCallback = new GattClientCallback();
                    mGatt = currDevice.connectGatt(getBaseContext(), false, gattClientCallback);
                    scanLeDevice(false);// will stop after first device detection
                }else{
                    //provo a ricollegarmi al dispositivo probabile, abbia perso la connessione con esso
                    scanLeDevice(true);
                }
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void connectToDevice(BluetoothDevice device) {
        //VERIFICO SE IL DEVICE è QUELLO CHE VOGLIO IO
        if (mGatt == null && settingApp != null
                && device.getAddress().equals(settingApp.getAddressBleSX())) {
            currDevice = device;
            GattClientCallback gattClientCallback = new GattClientCallback();
            mGatt = currDevice.connectGatt(getBaseContext(), false, gattClientCallback);
            scanLeDevice(false);// will stop after first device detection
        }
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    Handler h = new Handler(getApplicationContext().getMainLooper());
                    // Although you need to pass an appropriate context
                   //TO DO
                }
            };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void scanLeDevice(final boolean enable) {
        //TO DO
    }


    private ScanCallback mScanCallback = new ScanCallback() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
           //TODO
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private class GattClientCallback extends BluetoothGattCallback {

        @SuppressLint("LongLogTag")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            try{
                //TODO
            }catch(Exception e){
                Log.e("ON_CONNECTION_STATE_CHANGE", e.getMessage());
            }
        }

        public void disconnectGattServer() {
            valore = false;
            if (mGatt != null) {
                mGatt.disconnect();
                mGatt.close();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        //TODO
        }

        private void ReadCharacteristics(int index) {
            mGatt.readCharacteristic(ReadQueue.get(index));
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
          //  Log.i("INFO", "Characteristic changed, " + characteristic.getUuid().toString());
            readCharacteristic(characteristic);
        }

        private void enableCharacteristicNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
           //TODO
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            //TODO
        }
    }
}

0 个答案:

没有答案