Android-приложение не работает через определенный промежуток времени в телефоне OPPO f1s

У меня есть приложение для Android, которое считывает данные и отправляет их на сервер, используя службу Intent, этот процесс работает на всех телефонах, кроме OPPO F1, в этом телефоне служба разрушается через некоторый промежуток времени, после того, как эти данные не получаются отправить на сервер. Я пробовал с обслуживанием переднего плана даже эту работу dint в этом телефоне.

public class CaptureDataActivity extends AppCompatActivity implements  GoogleApiClient.OnConnectionFailedListener,GoogleApiClient.ConnectionCallbacks,LocationListener {

private Context mContext;
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private ProgressDialog mProgressDialog;
private ProgressBar mProgressBar;
private RecyclerView mRecyclerView;
private String mCropId;
private String mCropName, mdeviceMACId;
private TextView mHint;
private BluetoothDevice mDevice;
private StringBuffer mResponseFromDevice = new StringBuffer();
private Session mSesssion;
private Handler mHandler;
private static final int DATA_FROM_DEVICE = 1;
private String ndviData, ndviErrorData, mDevieName;
private DataBaseOpenHelper mDbHelper;
private SQLiteDatabase db;
private ConnectionDetector mConnectionDetector;
private boolean deviceListIsFetched = false;
private int flag;
private boolean isReceiverRegistered=false;

private UUID myUUID;
private final String UUID_STRING_WELL_KNOWN_SPP =
        "00001101-0000-1000-8000-00805F9B34FB";

private ThreadConnectBTdevice myThreadConnectBTdevice;
private ThreadConnected myThreadConnected;
private NetworkChangeReceiver networkChangeReceiver;
 private GoogleApiClient googleApiClient;
 private  Location location,mLastLocation;
private static final int PERMISSION_ACCESS_LOCATION = 1;
LocationListener locationListener;

Double Longitute,Langitute;
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
String mLastUpdateTime;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_capture_data);
    createLocationRequest();
    mContext = this;
    mSesssion = new Session(mContext);
    if (googleApiClient == null)
    {
        Log.d("Location", "E");
        googleApiClient = new GoogleApiClient.Builder(CaptureDataActivity.this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

    }
    Typeface typeface = Typeface.createFromAsset(getAssets(), Session.externalFontPath);
    mConnectionDetector = ConnectionDetector.getInstances(mContext);

    networkChangeReceiver = new NetworkChangeReceiver();
    mDbHelper = new DataBaseOpenHelper(mContext);
    db = mDbHelper.getWritableDatabase();



    String[] projection = {
            DataBaseContract.FeedEntry._ID,
    };

    Cursor cursor = db.query(
            DataBaseContract.FeedEntry.TABLE_NAME,
            projection,
            null,
            null,
            null,
            null,
            null
    );

    Log.d("def", "No of records(1) " + cursor.getCount());


    if (getIntent() != null) {
        mCropId = getIntent().getStringExtra("crop_id");
        mCropName = getIntent().getStringExtra("crop_name");
    }

    Log.d("crop_id", mCropId);

    setSupportActionBar((Toolbar) findViewById(R.id.captureData_appBar));
    if (!mCropName.isEmpty()) getSupportActionBar().setTitle("Capture Data for " + mCropName);
    else getSupportActionBar().setTitle("Capture Data");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);


    mRecyclerView = (RecyclerView) findViewById(R.id.captureData_recyclerView);


    mProgressBar = (ProgressBar) findViewById(R.id.captureData_progressBar);


    mHint = (TextView) findViewById(R.id.captureData_hint);
    mHint.setTypeface(typeface);

    myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);




    mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == DATA_FROM_DEVICE) {
                String strReceived = (String) msg.obj;

                if (strReceived.contains("$TEE0x")) {


                    Log.d("abc", strReceived);
                    ndviData = strReceived.substring(strReceived.indexOf("$")).trim();




                    mHint.setTextColor(getResources().getColor(R.color.colorPomegranate));
                    mHint.setText("Error");

                    playSoundAndVibrate();


                } else {

                    if (strReceived.substring(strReceived.lastIndexOf(".") + 1).length() == 4) {

                        Log.d("abc", strReceived);
                        if (strReceived.contains(".")) {
                            Log.d("abc", strReceived.substring(strReceived.lastIndexOf(".")));
                            if (!strReceived.substring(strReceived.lastIndexOf(".")).contains(",")) {
                                ndviData = strReceived.substring(strReceived.lastIndexOf("."));


                                Log.d("abc", "LAST");
                                Log.d("abc time",Session.getCurrentDateAndTime());
                                Log.d("def", ndviData);

                                mHint.setText(ndviData);

                                if (saveDataInTheLocalDatabase(ndviData) > 0) {


                                    String[] projection = {
                                            DataBaseContract.FeedEntry._ID,
                                    };

                                    Cursor cursor = db.query(
                                            DataBaseContract.FeedEntry.TABLE_NAME,
                                            projection,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null
                                    );


                                    Log.d("def", "Data Inserted into the local database and the number of records became "+ cursor.getCount());

                                    if (mConnectionDetector.isConnectingToInternet()) {



                                        if(!CheckServiceRunning.isServiceRunning(mContext))
                                        {
                                            Log.d("ghi", "Service not running");
                                            Intent i=new Intent(mContext, MyIntentService.class);
                                            startService(i);


                                        }
                                        else
                                        {
                                            Log.e("ghi", "Service already running");

                                            Intent i=new Intent(mContext, MyIntentService.class);
                                            stopService(i);

                                        }
                                    } else {


                                        if(!isReceiverRegistered)
                                            registerReceiver();




                                    }
                                } else {
                                    Log.d("Row", "Not Inserted");
                                }}
                        }

                    }

                }

            }
        }

    };

}

private void playSoundAndVibrate() {
    ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(500);
    Uri defaultRingtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    MediaPlayer mediaPlayer = new MediaPlayer();

    try {
        mediaPlayer.setDataSource(mContext, defaultRingtoneUri);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
        mediaPlayer.prepare();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });
        mediaPlayer.start();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


}

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();

    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
    googleApiClient.disconnect();
}



private void registerReceiver()
{
    isReceiverRegistered=true;
    registerReceiver(networkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

private long saveDataInTheLocalDatabase(String ndviData) {
    ContentValues values = new ContentValues();
    values.put(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_NDVI_VALUE, ndviData);
    values.put(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_ID, mCropId);
    values.put(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_NAME, mCropName);
    values.put(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_CITY, mSesssion.getUserCity());
    values.put(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_SUB_LOCALITY, mSesssion.getSubCity());
    values.put(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_LATITUDE, this.Langitute);
    values.put(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_LONGITUDE, this.Longitute);
    values.put(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_CREATED_AT, Session.getCurrentDateAndTime());
    Log.d("Date and time", Session.getCurrentDateAndTime());
    return db.insert(DataBaseContract.FeedEntry.TABLE_NAME, null, values);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_ENABLE_BT:
            if (resultCode == RESULT_OK) {
                scanAndPairDevice();
            } else {
                Toast.makeText(mContext, "Bluetooth is not enabled", Toast.LENGTH_SHORT).show();
                finish();

            }

    }

}

private boolean isDevicePaired() {

    Set<BluetoothDevice> bluetoothDeviceSet = mBluetoothAdapter.getBondedDevices();
    if (bluetoothDeviceSet.size() > 0) {

        Set<String> set=mSesssion.getDeviceList();
        Iterator<BluetoothDevice> iT=bluetoothDeviceSet.iterator();
        while(iT.hasNext()){

            BluetoothDevice device=iT.next();
            for(String device1: set)
            {
                if(device.getName().equals("SPLTECH"))
                {
                    flag=1;
                }

                if(device.getAddress().equals(device1))
                {

                    mDevice = device;
                    mSesssion.setDeviceMacId(device.getAddress());
                    return true;
                }

            }

        }
    }
    return false;
}

private void scanAndPairDevice() {
    if (isDevicePaired()) {
        receiveDataFromDevice();

    } else {

        if(flag!=1) {

            showAlertDialog(mContext, "SPLTECH Device is not paired!", "Please pair the device to connect", 1);
        }
        else {

            showAlertDialog(mContext, "SPLTECH Device is not registered!", "Please conect with a registered device", 3);
        }

    }
}

private void getDeviceListFromServer() {
    if (mConnectionDetector.isConnectingToInternet()) {
        StringRequest request = new StringRequest(Request.Method.POST, Session.baseURl + "", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                deviceListIsFetched = true;

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        SingletonVolley.getInstance(mContext).addToRequestQueue(request);
    } else
        deviceListIsFetched = false;

}

@Override
protected void onResume() {
    super.onResume();

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter != null) {
        if (!mBluetoothAdapter.isEnabled())
        {

            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {

            scanAndPairDevice();
        }

    } else {

    }
}


public void showAlertDialog(Context context, String title, String message, int type) {
    final android.app.AlertDialog alertDialog;
    alertDialog = new android.app.AlertDialog.Builder(mContext).create();

    alertDialog.setTitle(title);
    alertDialog.setMessage(message);

    alertDialog.setCancelable(false);

    if (type == 1) {
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                Intent settingsIntent = new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
                startActivity(settingsIntent);
            }
        });

    } else if (type == 2) {
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Retry", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                mHint.setText("Click to Capture Data!");
            }
        });

    } else if( type==3)
    {
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Retry", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                Intent settingsIntent = new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
                startActivity(settingsIntent);
            }
        });

        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                finish();
            }
        });
    }
    alertDialog.show();
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {


            final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
            final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); 

            if (deviceName.equalsIgnoreCase("SPLTECH")) {

                mDevieName = device.getName();
                ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                activityManager.killBackgroundProcesses("android.bluetooth");
            }
        }
    }
};



private void receiveDataFromDevice() {

    mProgressBar.setVisibility(View.GONE);
    mHint.setVisibility(View.VISIBLE);
    Toast.makeText(mContext, "Now,Bluetooth is Ready to Take Value From Device..!", Toast.LENGTH_SHORT).show();

    myThreadConnectBTdevice = new ThreadConnectBTdevice();
    myThreadConnectBTdevice.start();
}


@Override
public void onConnected(@Nullable Bundle bundle)
{
    checkBuiildVersionAndAccessLocation();

}


private void checkBuiildVersionAndAccessLocation() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (!checkPermission()) {
            Log.d("Location", "A");
            requestPermission();
        } else {
            Log.d("Location", "B");

            gettingLocation();
        }
    } else {
        Log.d("Location", "C");
        gettingLocation();

    }
}


private void requestPermission()
{

    if (ActivityCompat.shouldShowRequestPermissionRationale(CaptureDataActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(CaptureDataActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)) {

        Toast.makeText(CaptureDataActivity.this, "Allow permission to access location", Toast.LENGTH_LONG).show();
        ActivityCompat.requestPermissions(CaptureDataActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_ACCESS_LOCATION);

    } else {

        ActivityCompat.requestPermissions(CaptureDataActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_ACCESS_LOCATION);
    }
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    switch (requestCode) {
        case PERMISSION_ACCESS_LOCATION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(CaptureDataActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
                if (checkPermission()) {

                    gettingLocation();

                } else {
                    Toast.makeText(CaptureDataActivity.this, "Permission not granted", Toast.LENGTH_SHORT).show();
                }

            } else{
                Toast.makeText(CaptureDataActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
    }
}


public void gettingLocation()
{
    if (checkPermission())
    {
        Log.d("Location", "F");



        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);














    }
}






private boolean checkPermission() {
    if (Build.VERSION.SDK_INT >= 23) {
        int result = ContextCompat.checkSelfPermission(CaptureDataActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
        int result1 = ContextCompat.checkSelfPermission(CaptureDataActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
        if (result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED)
            return true;
        else
            return false;
    } else
        return true;

}


@Override
public void onConnectionSuspended(int i)
{

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{

}

@Override
public void onLocationChanged(Location location) {
    this.location=location;



    update_ui();
}

private void update_ui()
{
    if(location!=null)
    {
         this.Langitute=location.getLatitude();
        this.Longitute=location.getLongitude();

    }else
    {
        Toast.makeText(CaptureDataActivity.this,"LocaTION NULL",Toast.LENGTH_SHORT).show();

    }
}


private class ThreadConnectBTdevice extends Thread {

    private BluetoothSocket bluetoothSocket = null;

    private ThreadConnectBTdevice() {

        try {
            Log.i("hii","hello");
            bluetoothSocket = mDevice.createRfcommSocketToServiceRecord(myUUID);

        } catch (IOException e) {

            Log.i("hii","hello");
            e.printStackTrace();

        }
    }

    @Override
    public void run() {
        boolean success = false;
        try {
            bluetoothSocket.connect();
            success = true;
        } catch (IOException e)
        {
            e.printStackTrace();

            final String eMessage = e.getMessage();
            runOnUiThread(new Runnable() {

                @Override
                public void run() {


                }
            });


            try{
                bluetoothSocket.close();

            }
            catch (IOException ex)
            {

            }

        }

        if (success) {

            startThreadConnected(bluetoothSocket);
        } else {


            Log.i("fail","in false");


        }
    }

    public void cancel() {

        try {
            bluetoothSocket.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}


private void startThreadConnected(BluetoothSocket socket) {

    myThreadConnected = new ThreadConnected(socket);
    myThreadConnected.start();
}

private class ThreadConnected extends Thread {
    private final BluetoothSocket connectedBluetoothSocket;
    private final InputStream connectedInputStream;
    private final OutputStream connectedOutputStream;

    public ThreadConnected(BluetoothSocket socket) {

        connectedBluetoothSocket = socket;
        InputStream in = null;
        OutputStream out = null;

        try {
            in = socket.getInputStream();
            out = socket.getOutputStream();
        } catch (IOException e) {

            e.printStackTrace();
        }

        connectedInputStream = in;
        connectedOutputStream = out;
    }

    @Override
    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;


        while (true) {
            try {

                bytes = connectedInputStream.read(buffer);
                final String strReceived = new String(buffer, 0, bytes);

                Log.d("abc", strReceived);

                Message readMsg = mHandler.obtainMessage(
                        DATA_FROM_DEVICE, strReceived);
                readMsg.sendToTarget();

            } catch (IOException e) {

                e.printStackTrace();


                final String msgConnectionLost = "Connection lost:\n"
                        + e.getMessage();

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mHint.setText(msgConnectionLost);
                    }
                });

                break;
            }
        }

    }

    public void write(byte[] buffer) {
        try {
            connectedOutputStream.write(buffer);
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public void cancel() {
        try {
            connectedBluetoothSocket.close();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}

private void updateData(final String ndviDeviceData) {
    StringRequest allDealsStringRequest = new StringRequest(Request.Method.POST, Session.baseURl + "ndvi_data.php?type=1", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            mProgressDialog.dismiss();
            if (response != null && !response.isEmpty()) {
                try {
                    Log.d("abc", response);
                    JSONObject jsonObject = new JSONObject(response);

                    if (jsonObject.getString("Response").equalsIgnoreCase("Success")) {

                        if (ndviDeviceData.contains("$TEE0x"))
                            mHint.setText("Error in fetching Data!\nError Code- " + ndviDeviceData + "\nPlease try again...");
                        else
                            mHint.setText("NDVI Value- 0" + ndviData);

                    } else showAlertDialog(mContext, "Error", "Please try again later", 2);

                } catch (JSONException e) {
                    e.printStackTrace();
                    showAlertDialog(mContext, "Error", "Please try again later", 2);

                }

            } else showAlertDialog(mContext, "Error", "Please try again later", 2);


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mProgressDialog.dismiss();
            showAlertDialog(mContext, "Error", "Please try again later", 2);


        }
    }) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();

            Log.d("abc", mSesssion.getUserId() + " " + ndviDeviceData + " " + mCropId);

            params.put("user_id", mSesssion.getUserId());
            params.put("device_id", "1234");
            params.put("ndvi_data", ndviDeviceData.trim());
            params.put("location", "Bangalore");
            params.put("crop_id", mCropId);
            return params;
        }
    };

    allDealsStringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    SingletonVolley.getInstance(mContext).addToRequestQueue(allDealsStringRequest);
}


@Override
protected void onDestroy() {
    super.onDestroy();

    if (myThreadConnectBTdevice != null) {
        myThreadConnectBTdevice.cancel();
    }

    mBluetoothAdapter.disable();

}

@Override
protected void onPause() {
    super.onPause();
    if (myThreadConnectBTdevice != null) {
        myThreadConnectBTdevice.cancel();
    }

    try {
        unregisterReceiver(networkChangeReceiver);
    } catch (IllegalArgumentException e) {

    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
    }
    return false;
}



protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}

1 ответ

ИНТЕНТ СЕРВИС

public class MyIntentService extends IntentService {

private SQLiteDatabase mDB;
private DataBaseOpenHelper mDbHelper;
private Context mContext;
private String mCropNdviValue, mCropName, mCropId, mCropLat="", mCropLong="", mCropCity="", mCropSubCity="", mCropCreatedAt;
private long mRecordId;
private Session mSession;
private boolean isDataUploaded = false;
String threeSecTime="",latestInsertedValue="";



public MyIntentService() {
    super("MyIntentService");
}

@Override
public void onCreate() {
    super.onCreate();
    mContext = MyIntentService.this;
    mDbHelper = new DataBaseOpenHelper(mContext);
    mDB = mDbHelper.getWritableDatabase();
    mSession = new Session(mContext);

    Log.e("def", "Service is created");
}

@Override
protected void onHandleIntent(Intent intent) {
    while (isDataPresent())
    {
        Log.d("def", "Service starts since data is yet to be uploaded");

        fetchRecordAndUpload();
        Notification notification =
                new Notification.Builder(this)
                        .setContentTitle("Service Status")
                        .setContentText("Service running")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .build();

        startForeground(102, notification);



    }
    Log.d("def", "Service stops since no data is present");
    stopSelf();
}

private boolean isDataPresent() {


    Log.d("def", "isDataPresent is called");
    String[] projection = {
            DataBaseContract.FeedEntry._ID,
    };



    if (mDB != null) {
        Cursor cursor = mDB.query(
                DataBaseContract.FeedEntry.TABLE_NAME,
                projection,
                null,
                null,
                null,
                null,
                null
        );

        if (cursor.getCount() > 0) {

            return true;

        }
        cursor.close();
    }
    return false;
}

private synchronized void fetchRecordAndUpload() {

    String[] projection = {
            DataBaseContract.FeedEntry._ID,
            DataBaseContract.FeedEntry.COLUMN_NAME_CROP_NDVI_VALUE,
            DataBaseContract.FeedEntry.COLUMN_NAME_CROP_NAME,
            DataBaseContract.FeedEntry.COLUMN_NAME_CROP_ID,
            DataBaseContract.FeedEntry.COLUMN_NAME_CROP_LATITUDE,
            DataBaseContract.FeedEntry.COLUMN_NAME_CROP_LONGITUDE,
            DataBaseContract.FeedEntry.COLUMN_NAME_CROP_CITY,
            DataBaseContract.FeedEntry.COLUMN_NAME_CROP_SUB_LOCALITY,
            DataBaseContract.FeedEntry.COLUMN_NAME_CROP_CREATED_AT
    };

    if (mDB != null) {

        Cursor cursor = null;
        try {
            cursor = mDB.query(
                    DataBaseContract.FeedEntry.TABLE_NAME,
                    projection,
                    null,
                    null,
                    null,
                    null,
                    null
            );


            Log.d("def", "No of records(4) " + cursor.getCount());

            int count = 0;

            while (cursor.moveToNext()) {


                Log.e("def", "While loop starts for " + count);

                mRecordId = cursor.getLong(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry._ID));
                mCropNdviValue = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_NDVI_VALUE));
                mCropName = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_NAME));
                mCropId = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_ID));

                mCropLat = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_LATITUDE));
                mCropLong = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_LONGITUDE));
                mCropCity = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_CITY));
                mCropSubCity = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_SUB_LOCALITY));
                mCropCreatedAt = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.FeedEntry.COLUMN_NAME_CROP_CREATED_AT));
                Log.d("def", "Record id fetched from db- " + mRecordId + " Ndvi data- " + mCropNdviValue);

                uploadToServer();
                isDataUploaded = false;
                while (!isDataUploaded) {
                }
                Log.e("def", "While loop ends for " + count);
                count++;
            }

        } finally {
            cursor.close();
        }

    }
}


private void uploadToServer() {


    StringRequest allDealsStringRequest = new StringRequest(Request.Method.POST, Session.baseURl + "ndvi_data_time_insert.php?type=1", new Response.Listener<String>() {

        @Override
        public void onResponse(String response)
        {
            if (response != null && !response.isEmpty())
            {
                try {

                    JSONObject jsonObject = new JSONObject(response);
                    Log.i("response",response);
                    if (jsonObject.getString("Response").equalsIgnoreCase("Success"))
                    {

                        Log.d("def", response);
                        threeSecTime=jsonObject.getString("three_sec_time");
                        mSession.setthreesectime("");
                        if(threeSecTime!=null && threeSecTime!="") {
                            mSession.setthreesectime(threeSecTime);
                        }
                        Log.i("three",threeSecTime);
                        if (deleteRecordFromLocalDB())
                        {
                            Log.d("def", "Record is deleted");
                            isDataUploaded = true;
                        }

                    } else {
                        Log.d("abc", response);

                    }

                } catch (JSONException e) {

                    Log.d("def", "91 " + e.getMessage());
                    e.printStackTrace();


                }

            } else {
                Log.d("def", "99");

            }


        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            isDataUploaded = true;
            Log.d("def", "56 " + error.getMessage());



        }
    }) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            Log.d("def", "getParams- " + mSession.getUserId() + " " + mCropNdviValue + " " + mCropCity + " " + mCropLat + " " + mCropLong + " " + mCropSubCity + " " + mCropId + " " + mCropCreatedAt + " " + " " + mSession.getDeviceMacId() + " "+mSession.getthreesectime()+" "+mSession.getpreviousid());
            params.put("user_id", mSession.getUserId());
            params.put("device_id", mSession.getDeviceMacId());
            params.put("ndvi_data", mCropNdviValue.trim());
            if(mCropCity!=null)
            {
                params.put("location", mCropCity.trim());
            }
            else
            {
                params.put("crop_latitude", "");
            }
            if(mCropLat!=null)
            {
                params.put("crop_latitude", mCropLat.trim());
            }else
            {
                params.put("crop_latitude", "");
            }
            if(mCropLong!=null)
            {
                params.put("crop_longitude", mCropLong.trim());
            }else
            {
                params.put("crop_longitude", "");

            }
            if(mCropSubCity!=null)
            {
                params.put("crop_sub_locality", mCropSubCity.trim());
            }else
            {
                params.put("crop_sub_locality", "");

            }
            params.put("crop_id", mCropId.trim());
            params.put("crop_name", mCropName.trim());
            params.put("created_at", mCropCreatedAt.trim());
            params.put("three_update_date",mSession.getthreesectime());





            return params;
        }
    };

    allDealsStringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    SingletonVolley.getInstance(mContext).addToRequestQueue(allDealsStringRequest);

}

private boolean deleteRecordFromLocalDB() {

    String selection = DataBaseContract.FeedEntry._ID + " LIKE ?";
    String[] selectionArgs = {String.valueOf(mRecordId)};
    return (mDB.delete(DataBaseContract.FeedEntry.TABLE_NAME, selection, selectionArgs) > 0);
}


@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("def", "Service is destroyed");

}
}
Другие вопросы по тегам