Android 服务被阻止了

Android 服务被阻止了,android,service,bluetooth-lowenergy,Android,Service,Bluetooth Lowenergy,我正在构建一个服务,每次下载一个可存储设备的所有信息,并将这些数据存储到本地数据库中 现在我正在构建一个服务来完成这项工作。如果我尝试在Android Studio的调试中启动我的应用程序,它永远不会出错。我尝试在后台做我的应用程序约3小时,服务保存所有信息,服务未锁定 现在,我正在构建一个APK文件,我正在尝试将其安装到同一个Android设备中,但该服务只运行一次,之后就不会执行了 我正在用Android 7.0测试三星J3 我有什么问题 这是我的BlePowerService.java:

我正在构建一个服务,每次下载一个可存储设备的所有信息,并将这些数据存储到本地数据库中

现在我正在构建一个服务来完成这项工作。如果我尝试在Android Studio的调试中启动我的应用程序,它永远不会出错。我尝试在后台做我的应用程序约3小时,服务保存所有信息,服务未锁定

现在,我正在构建一个APK文件,我正在尝试将其安装到同一个Android设备中,但该服务只运行一次,之后就不会执行了

我正在用Android 7.0测试三星J3

我有什么问题

这是我的BlePowerService.java:

public class BlePowerService extends Service {
    public DbLayer db;
    Setting settingApp;
    List<ScanFilter> filters;
    String[] stringSequence = new String[] {CHARACTERISTIC_FORZA_STRING, CHARACTERISTIC_TEMPERATURA_STRING};
    BluetoothAdapter mBluetoothAdapter;
    BluetoothGatt mGatt;
    BluetoothDevice currDevice;
    static final long SCAN_PERIOD = 500;
    static String SPLIT_CHAR =";";
    BluetoothLeScanner mLEScanner;
    Handler mHandler;
    int ReadQueueIndex;
    List<BluetoothGattCharacteristic> ReadQueue;
    BluetoothGattCharacteristic caratteristicaDaLeggere;
    ScanSettings settings;
    Integer ultimaForzaLetta,ultimaTemperaturaLetta;
    boolean continuaLetturaForza, continuaLetturaTemperatura;
    boolean isReading = true;
    String LOG_CODE = "NOTIFSRV";
    GattClientCallback gattClientCallback;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;


    public BlePowerService() {
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler();

        Context sharedContext = null;
        try {
            sharedContext = this.createPackageContext(
                    "com.care.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;
        }
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            //RECUPERO LE IMPOSTAZIONI SETTATE DALL'UTENTE
            settingApp = db.fetchSetting();
            if (settingApp != null && settingApp.getAddressBleSX()!=null) {
                //POSSO FILTRARE DIRETTAMENTE PER L'UUID DEL DISPOSITIVO MEMORIZZATO
                //DALL'UTENTE
                ScanFilter.Builder scanFilterMac =
                        null;
                    scanFilterMac = new ScanFilter.Builder().setDeviceAddress(settingApp.getAddressBleSX());
                if(filters==null)
                    filters = new ArrayList<ScanFilter>();
                //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                filters.add(scanFilterMac.build());
                //}
                //FILTRO ANCHE PER LA CARATTERISTICA DI FORZA
                ScanFilter filter = null;
                    filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(CHARACTERISTIC_FORZA_STRING)).build();
                filters.add(filter);

                final BluetoothManager bluetoothManager =
                        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
                    mBluetoothAdapter = bluetoothManager.getAdapter();
                //mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                    mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                    settings = new ScanSettings.Builder()
                            .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                            .build();
                scanLeDevice(true);
                mTimer = new Timer();
                //ogni 2 ore
                continuaLetturaForza = true;
                continuaLetturaTemperatura = true;

                int nSecondi = settingApp.getFrequenzaDownload()!= null ? settingApp.getFrequenzaDownload() : 1;
                //mTimer.schedule(timerTask, 10000, 1000 * nSecondi);
                mTimer.scheduleAtFixedRate (timerTask, 10000, 1000 * nSecondi);
            }
        } 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
             int counter = 0;
            while(continuaLetturaForza || continuaLetturaTemperatura){
                counter++;
                //Log.v("CICLO WHILE", counter+"");
                if (currDevice != null) {

                    if(ReadQueue!= null && ReadQueue.size()>0){
                        int index =0;
                        for(index=0; index < ReadQueue.size(); index++){
                            if(mGatt!=null){
                                isReading = mGatt.readCharacteristic(ReadQueue.get(index));
                                while(isReading){
                                    try {
                                        Thread.sleep(1);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }else{
                                continuaLetturaForza = false;
                                continuaLetturaTemperatura = false;
                            }
                        }
                    }
              }else{
                    //provo a ricollegarmi al dispositivo probabile, abbia perso la connessione con esso
                    scanLeDevice(true);
                    try {
                        Thread.sleep(2500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(currDevice == null && counter == 25){
                        //in questo caso non è riuscito a trovare il dispositivo BLE
                        //esco dal ciclo
                        continuaLetturaForza = false;
                        continuaLetturaTemperatura = false;
                        continue;
                    }
                }
            }
             if(gattClientCallback!=null && mGatt != null)
                gattClientCallback.disconnectGattServer();

        }

        public void stopTask() {

            if (timerTask != null) {

                Log.d("TIMER", "timer canceled");
                timerTask.cancel();
            }
        }
    };


    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 = 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
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                          //  Log.i("onLeScan", device.toString());
                                connectToDevice(device);

                        }
                    });
                }
            };

    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);
            }
        }
    }


    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 = null;
               btDevice = result.getDevice();
            connectToDevice(btDevice);
        }

        @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 class GattClientCallback extends BluetoothGattCallback {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            try{
                super.onConnectionStateChange(gatt, status, newState);
                //Log.i("tag", "onConnectionStateChange newState: " + newState);

                if (status == BluetoothGatt.GATT_FAILURE) {
                    Log.e("ERROR_SERVICE", "Connection Gatt failure status " + status);
                    if(mGatt == null){

                    }else{
                        try {
                            gatt.close();
                        } catch (Exception e) {
                            Log.d("", "close ignoring: " + e);
                        }
                        mGatt = null;
                    }
                    return;
                } else if (status != BluetoothGatt.GATT_SUCCESS) {
                    // handle anything not SUCCESS as failure
                    Log.e("ERROR_SERVICE", "Connection not GATT sucess status " + status);
                    if(mGatt == null){

                    }else{
                        try {
                            gatt.close();
                        } catch (Exception e) {
                            Log.d("", "close ignoring: " + e);
                        }
                        mGatt = null;
                    }
                    return;
                }

                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    //Log.i("INFO", "Connected to device " + gatt.getDevice().getAddress());
                    gatt.discoverServices();
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    Log.i("INFO", "Disconnected from device");
                    if(mGatt == null){

                    }else{
                        try {
                            mGatt.close();
                            mGatt = null;
                            currDevice = null;
                        } catch (Exception e) {
                            Log.d("", "close ignoring: " + e);
                        }
                        mGatt = null;
                    }

                }
            }catch(Exception e){
                Log.e("tag", e.getMessage());
                continuaLetturaForza = true;
                continuaLetturaTemperatura = true;
            }
        }

        public void disconnectGattServer() {
            //Log.i("INFo", "Closing Gatt connection");
            //  clearLogs();
            //mConnected = false;
            //mEchoInitialized = false;
            continuaLetturaForza = true;
            continuaLetturaTemperatura = true;
            isReading = false;
            if (mGatt == null) {

            }
            else{
                try{
                    mGatt.disconnect();
                   // mGatt.close();
                }catch(Exception e){
                    mGatt = null;
                }

            }
            //mGatt = null;
            //currDevice = null;
        }

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

            if (status != BluetoothGatt.GATT_SUCCESS) {
             //   Log.i("INFO", "Device service discovery unsuccessful, status " + status);
                return;
            }

            List<BluetoothGattCharacteristic> matchingCharacteristics =
                    BluetoothUtils.findCharacteristics(gatt,stringSequence);
            if (matchingCharacteristics.isEmpty()) {
              //  Log.e("ERROR_SERVICE","Unable to find characteristics.");
                return;
            }else {

                //INIZIALIZZO LA LISTA DI CARATTERISTICHE CHE DEVO ANDARE A LEGGERE
                ReadQueue = new ArrayList<>();
                for (BluetoothGattCharacteristic characterist : matchingCharacteristics) {
                    ReadQueue.add(characterist);
                }
                //ReadQueueIndex = 0;
                //ReadCharacteristics(ReadQueueIndex);
            }



        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
              String valoreRestituito = characteristic.getStringValue(0);
                if(valoreRestituito==null){
                    int i = 0;
                    i = i + 1;
                    return;
                }
                //SPLITTO PER IL CARATTERE ;
                String[] arrayValori = valoreRestituito.split(SPLIT_CHAR);
                //1 valore è l ID
                try{
                    int id = new Integer(arrayValori[0]);
                    //VERIFICO SE STO LEGGENDO TEMPERATURA O FORZA
                    if(characteristic.getUuid().equals(CHARACTERISTIC_FORZA_UUID)){
                        /*Log.v("CARATTERISTICA", "*****************************************");
                        Log.v("FORZA", "*****************************************");*/
                        if(ultimaForzaLetta!= null && ultimaForzaLetta == id){
                            continuaLetturaForza = false;
                            isReading = false;
                            return;
                        }
                        ultimaForzaLetta = id;
                    }else if(characteristic.getUuid().equals( CHARACTERISTIC_TEMPERATURA_UUID)){
                        /*Log.v("CARATTERISTICA", "*****************************************");
                        Log.v("TEMPERATURA", "*****************************************");*/
                        if(ultimaTemperaturaLetta!= null && ultimaTemperaturaLetta == id){
                            continuaLetturaTemperatura = false;
                            isReading = false;
                            return;
                        }
                        ultimaTemperaturaLetta = id;
                    }

                    SensorData mSenData = new SensorData();
                    mSenData.setIdType(id);
                    mSenData.setValue1(arrayValori[1]);
                    mSenData.setValue2(arrayValori[2]);
                    mSenData.setValue3(arrayValori[3]);
                    mSenData.setValue4(arrayValori[4]);
                    mSenData.setValue5(arrayValori[5]);
                    mSenData.setValue6(arrayValori[6]);
                    mSenData.setValue7(arrayValori[7]);
                    mSenData.setValue8(arrayValori[8]);
                    //TO-DO HO COMMENTATO QUESTA RIGA DI CODICE
                    // mSenData.setIdType(st.getId());
                    mSenData.setCharacteristic(characteristic.getUuid().toString());
                    mSenData.setValueTimestamp(db.getDateTime(true));
                    //inserisco i dati nel db
                        db.insertSensorData(mSenData);

                    EventBus.getDefault().post(new MessageEvent("update"));

                    //EventBus.getDefault().post(new UnfriendEvent(userId));
                }catch (Exception e){
                    Log.e("ERROR", e.getMessage());
                }
                isReading = false;

            } else {
                isReading = false;
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
               disconnectGattServer();

                return;
            }
        }

    }

    public void onDestroy() {
        try {
            db.close();
            Log.d(LOG_CODE,"DB connection closed" );

            mTimer.cancel();
            timerTask.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
公共类BlePowerService扩展服务{
公共数据层数据库;
设置应用程序;
列表过滤器;
String[]stringSequence=新字符串[]{CHARACTERISTIC\u FORZA\u String,CHARACTERISTIC\u TEMPERATURA\u String};
蓝牙适配器mBluetoothAdapter;
蓝牙关贸总协定;
蓝牙设备;
静态最终长扫描周期=500;
静态字符串拆分_CHAR=“;”;
蓝牙扫描仪;
汉德勒;
int-ReadQueueIndex;
列表读取队列;
蓝牙特征性卡拉特氏菌;
扫描设置;
整数ultimaForzaLetta,UltimateAmperaturaletta;
布尔连续温度场,连续温度场;
布尔值isReading=true;
字符串LOG_CODE=“NOTIFSRV”;
GattClientCallback GattClientCallback;
私有静态最终整数权限\请求\粗略\位置=1;
公共电力服务(){
}
@凌驾
公共IBinder onBind(意向){
//TODO:将通信通道返回到服务。
//抛出新的UnsupportedOperationException(“尚未实现”);
返回null;
}
@凌驾
public void onCreate(){
super.onCreate();
mHandler=新处理程序();
上下文sharedContext=null;
试一试{
sharedContext=this.createPackageContext(
“com.care.devicesensor”,
上下文。上下文(包括代码);
if(sharedContext==null){
返回;
}
db=新的数据库层(sharedContext);
db.open();
}捕获(例外e){
字符串错误=e.getMessage();
//Log.d(日志代码,“DB错误:+错误);
返回;
}
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
试一试{
//这是一个很好的解释
settingApp=db.fetchSetting();
if(settingApp!=null&&settingApp.getAddressBleSX()!=null){
//每一个处置者都有一辆罕见的汽车
//达尔登特
ScanFilter.Builder scanFilterMac=
无效的
scanFilterMac=new ScanFilter.Builder().setDeviceAddress(settingApp.getAddressBleSX());
if(过滤器==null)
过滤器=新的ArrayList();
//if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.LOLLIPOP){
filters.add(scanFilterMac.build());
//}
//每平方英尺的过滤
扫描过滤器=空;
filter=new ScanFilter.Builder().setServiceUuid(parcelouid.fromString(CHARACTERISTIC_FORZA_STRING)).build();
过滤器。添加(过滤器);
最终BluetoothManager BluetoothManager=
(BluetoothManager)getSystemService(Context.BLUETOOTH\u服务);
mBluetoothAdapter=bluetoothManager.getAdapter();
//mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
mLEScanner=mBluetoothAdapter.getBluetoothLeScanner();
设置=新的ScanSettings.Builder()
.setScanMode(扫描设置.扫描模式\u低功率)
.build();
扫描设备(真实);
mTimer=新计时器();
//奥格尼2号矿石
continuealetturaforza=true;
连续温度A=真;
int nSecondi=settingApp.getFrequenzaDownload()!=null?settingApp.getFrequenzaDownload():1;
//mTimer.时间表(timerTask,10000,1000*N秒);
mTimer.scheduleAtFixedRate(timerTask,10000,1000*n秒);
}
}捕获(例外e){
//Log.e(“POWER_服务”,e.getMessage());
}
返回super.onStartCommand(intent、flags、startId);
}
私人定时器;
TimerTask TimerTask=新TimerTask(){
@RequiresApi(api=Build.VERSION\u code.JELLY\u BEAN\u MR2)
@凌驾
公开募捐{
//莱戈·图蒂(LEGGO TUTTI I DATI DAL Sensor of FINCHE CI SONO VALORI)
int计数器=0;
while(continuaLetturaForza | | continualetturatemperaturea){
计数器++;
//Log.v(“CICLO WHILE”,counter+”);
if(currDevice!=null){
if(ReadQueue!=null&&ReadQueue.size()>0){
int指数=0;
对于(索引=0;索引