Soru & Cevap

Android Servis Arka Planda Çalışmıyor

05.08.2017 - 06:48

Merhaba Arkadaşlar Android servis oluşturdum. Bu servis konum güncellenince  api çağırıyor ve veri kaydediyor. Uygulama ön planda olunca sorun yok ancak arka plana alınca servisim çalışmıyor . Sebebi ne  olabilir ? Servisim aşağıdaki gibidir.

 


public class VehicleGPSTrackerService extends Service {

    private LocationListener listener;
    private LocationManager locationManager;
    boolean gps_enabled = false;
    private Location llocation;
    private static final long MIN_TIME_BW_UPDATES = 1000 * 5 * 1; // 5 saniye

    public Coordinate lastCoordinate;

    TelephonyManager mTelephonyManager;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(this,getBaseContext().getResources().getString(R.string.tracking_on_started), Toast.LENGTH_SHORT).show();
        Log.e("onStartCommand", "GPS Service onStartCommand");

        lastCoordinate = new Coordinate();
        lastCoordinate.Latitude =0;
        lastCoordinate.Longitude = 0;

        try {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);


            if(!isNetworkAvailable(getBaseContext()))
            {
                Intent i = new Intent("location_update");
                i.putExtra("status", getBaseContext().getResources().getString(R.string.internet_connection_notfound));
                sendBroadcast(i);
            }

            if(!gps_enabled)
            {
                Intent i = new Intent("location_update");
                i.putExtra("status",  getBaseContext().getResources().getString(R.string.cannot_gps_data));
                sendBroadcast(i);
            }


            if (isNetworkAvailable(getBaseContext()) && gps_enabled)
            {
                if (locationManager != null) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                        return Service.START_STICKY;
                    }
                    llocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
                    updateWithNewLocation(llocation);
                    //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,0, this.listener);
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,0, this.listener);
                }
            }
        }
        catch (Exception e)
        {
            Log.e("gpsserviceexception",e.getMessage());
        }

        return super.onStartCommand(intent, flags, startId);


    }

    public boolean isNetworkAvailable(final Context context) {
        final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
        return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
    }

    public void updateWithNewLocation(Location location)
    {
        listener = new LocationListener() {

            @Override
            public void onLocationChanged(Location location)
            {
                lastCoordinate = new Coordinate();
                double lat = location.getLatitude();
                double longi = location.getLongitude();
                lastCoordinate.Latitude =lat;
                lastCoordinate.Longitude = longi;

                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(location.getTime());
                String formatted = format.format(date);

                final JSONObject headerObject = new JSONObject();
                final JSONObject params = new JSONObject();
                try
                {
                    JSONObject coordinate = new JSONObject();
                    coordinate.put("Latitude",lastCoordinate.Latitude);
                    coordinate.put("Longitude",lastCoordinate.Longitude);

                    JSONArray jsonArrayLogs = new JSONArray();

                    params.put("Status", EnumHelpers.EnumStatus.Active.getValue());
                    params.put("Coordinate", coordinate);
                    params.put("LastInfoDate",formatted);

                    jsonArrayLogs.put(params);

                    headerObject.put("UserId", AppEngine.CURRENT_USER.getId());
                    headerObject.put("ActiveDeviceId",getDeviceImei());
                    headerObject.put("Details",jsonArrayLogs);

                    Log.e("AktiveData",headerObject.toString());

                    SentDataToVolley(headerObject);
                }
                catch (Exception e){}

                Intent i = new Intent("location_update");
                i.putExtra("status", getBaseContext().getResources().getString(R.string.active));
                sendBroadcast(i);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

                Intent i = new Intent("location_update");
                i.putExtra("status", getBaseContext().getResources().getString(R.string.active));
                sendBroadcast(i);
            }

            @Override
            public void onProviderDisabled(String provider) {

                final JSONObject headerObject = new JSONObject();
                final JSONObject params = new JSONObject();
                try
                {
                    JSONObject coordinate = new JSONObject();
                    coordinate.put("Latitude",0);
                    coordinate.put("Longitude",0);

                    JSONArray jsonArrayLogs = new JSONArray();

                    params.put("Status", EnumHelpers.EnumStatus.NoGpsSignal.getValue());
                    params.put("Coordinate", coordinate);
                    params.put("LastInfoDate",getCurrentDate());

                    jsonArrayLogs.put(params);

                    headerObject.put("UserId", AppEngine.CURRENT_USER.getId());
                    headerObject.put("ActiveDeviceId",getDeviceImei());
                    headerObject.put("Details",jsonArrayLogs);

                    Log.e("NoSignalData",headerObject.toString());

                    SentDataToVolley(headerObject);
                }
                catch (Exception e){}

                Intent i = new Intent("location_update");
                i.putExtra("status", getBaseContext().getResources().getString(R.string.cannot_gps_data));
                sendBroadcast(i);
            }
        };
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, getBaseContext().getResources().getString(R.string.stop_tracking), Toast.LENGTH_LONG).show();

        final JSONObject headerObject = new JSONObject();
        final JSONObject params = new JSONObject();
        try
        {
            JSONObject coordinate = new JSONObject();
            coordinate.put("Latitude",lastCoordinate.Latitude);
            coordinate.put("Longitude",lastCoordinate.Longitude);

            JSONArray jsonArrayLogs = new JSONArray();

            params.put("Status", EnumHelpers.EnumStatus.StopTracking.getValue());
            params.put("Coordinate", coordinate);
            params.put("LastInfoDate",getCurrentDate());

            jsonArrayLogs.put(params);

            headerObject.put("UserId", AppEngine.CURRENT_USER.getId());
            headerObject.put("ActiveDeviceId",getDeviceImei());
            headerObject.put("Details",jsonArrayLogs);

            Log.e("StopTrackingData",headerObject.toString());

            SentDataToVolley(headerObject);
        }
        catch (Exception e){}


        if(locationManager != null){
            //noinspection MissingPermission
            locationManager.removeUpdates(listener);
        }
    }

    public void SentDataToVolley(final JSONObject headerObject )
    {

        RequestQueue getRequestQueue = Volley.newRequestQueue(getApplicationContext());

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, UrlConfig.VOLLEY_MOBILEGPSLOG, headerObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response)
            {
                Log.e("onResponse", response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                VolleyLog.d("onErrorResponse", "Error: " + error.getMessage());
                Log.e("Oonfail", error.toString());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                headers.put("Authorization-Token", ConstansApi.API_KEY);
                return headers;
            }
        };
        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(60000,    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        // Adding request to request queue
        getRequestQueue.add(jsonObjReq);

    }

    public String getCurrentDate()
    {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = format.format(c.getTime());

        return strDate;
    }

    private String getDeviceImei() {

        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String deviceid = mTelephonyManager.getDeviceId();
        Log.d("msg", "DeviceImei " + deviceid);
        return deviceid;
    }

}

Bu servisi de şu şekilde çağırıyorum

 Intent i =new Intent(MainActivity.this,VehicleGPSTrackerService.class);
                startService(i);

manifast.xml dosyası da şu sekildedir

 <service
            android:name=".VehicleGPSTrackerService"
            android:enabled="true"
            android:exported="false"/>

 

48 Görüntülenme

1 Cevap

Sitedeki sorulara cevap verebilmek için giriş yapın ya da üye olun.

Profile picture for user m101
m101
14.12.2019 - 12:41

https://www.vogella.com/tutorials/AndroidServices/article.html böyle bir dökümantasyon buldum bunu inceleyebilirsiniz.