1

Hi i am android developer with just 3 months experience.I am developing a taxi app which needs to send user's latlong to server through webservice.I almost completed my project.But now i facing a new problem,I wrote the webservice in service class and call it from my activity,my problem is "the touch become irresponsive after the user moves to 5 km and then crashed like app is not responding".What i need is i want to send user's latlong for morethan 100 kms.i had added my logcat to show errors

I tested on two device.

1.First,In 1gb ram mobiles it crashes at 5 kms. 2.Second,In 2gb ram mobiles,it crashes at 30 kms.

Please anybody help, otherwise i will be fired from my office.

My acticity code with map is :

public class Mapforcalculation extends FragmentActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, View.OnClickListener {

                private LinearLayout lay_start_ride_lay;
                private Switch waiting,ac;
                private boolean act,dateforrow;
                private  long starttime,diffrence,secs,waitingtimefl,resultwait;
                private int luggage_chage;
                private GoogleApiClient mGoogleApiClient;
                private GoogleMap mGoogleMap;
                private Location Mylocation;
                private  String cust_name,Customer_Adress,custom_mobile,Ride_id,drive_id,vehic_id,s,url,finalAddsres,resendasy;
                 double responseeein,aa_actualfare,waitTimeFrae,Min_KM_ride,minimumFare,rateperkm,acrateperkm,nightminimrate,nightadd_minmrate,Acnightadd_mrate;
                private double  nightFare=0, addRatePerMinit=0,night_time_frm_hrs,night_time_to_hrs;
                private long attr;
                private double A_ActualFare,start_lat,start_long;
                private LocationRequest mLocationRequest;
                private Location location;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.driver_with_map_wait_cust);
                      keepScreenOn();
                     buildGoogleApiClient();
                    setLocationRequestMap();
                 }
               private void keepScreenOn() {
                    try {
              getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                protected synchronized void buildGoogleApiClient() {
               mGoogleApiClient = new GoogleApiClient.Builder(this)
                            .addConnectionCallbacks(this)
                            .addOnConnectionFailedListener(this)
                            .addApi(LocationServices.API)
                            .build();
                }
                @Override
                public void onClick(View view) {
                    /*new Calculationtask().execute();*/
                    Dayornight();
                    gettingdistanec();
                    rideEndVolly(aa_actualfare);

                }

                @Override
                public void onConnected(@Nullable Bundle bundle) {
            Log.i("connected","connected");

                    startLocationUpdates();
             Intent intent = new Intent(this,Serviceafterstartbutton.class);         
                    intent.putExtra("Ride_id",Ride_id);
                    this.startService(intent);
                }
           @Override
                public void onLocationChanged(Location location) {   }
            @Override
                protected void onResume() {
                    super.onResume();
                    if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
                         buildGoogleApiClient();
                        mGoogleApiClient.connect();

                    }
                    if (mGoogleMap == null) {
                        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.maps);
             mapFragment.getMapAsync(this);
                    }
                }

                @Override
                public void onMapReady(GoogleMap googleMap) {
                    mGoogleMap = googleMap;
                    mGoogleMap.setPadding(0, 5, 0, 5);
                    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    mGoogleMap.setTrafficEnabled(true);
                    mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
                    mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
                    mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
                    mGoogleMap.getUiSettings().setCompassEnabled(true);
                    mGoogleMap.setMyLocationEnabled(true);
                    mGoogleMap.getUiSettings().setAllGesturesEnabled(true);

                    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    Log.i("onmsppreddy","onmappreddy");
                }
                private void Dayornight() {
                  long timeInMillis = System.currentTimeMillis();
                    Calendar cal1 = Calendar.getInstance();
                    cal1.setTimeInMillis(timeInMillis);
                    SimpleDateFormat dateFormat = new SimpleDateFormat("HH");
                    String dateforrowwww = dateFormat.format(cal1.getTime());
                    long datee= Long.parseLong(dateforrowwww);
                    Log.d("datee", " url :" + datee);
                    if(datee >= 5 && datee < 22){
                        /*dateforrow="Day";*/
                        dateforrow=true;
                        Log.d("datefrw", " url :" + dateforrow);
                    }
                    else
                    {
                        dateforrow=false;
                    }
                }
                private void  gettingdistanec() {
           final String url = Api_url.url_link +"dist_km.php?driverid="+ drive_id+"&vehicle_id="+vehic_id+"&ride_id="+Ride_id;
                    Log.d("URL_P", url);

                    final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            try{
                                String rresponseee=response.getString("km");
                                Log.d("OVER", "km : " + response);

                                if(rresponseee!= null) {
                                    responseeein =  Double.valueOf(rresponseee);
                                    calculatefinalfare(responseeein);
                                }

                               }catch(Exception e){
                                Log.d("OVERRR", "errorr : " + e);                }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
                    setRetyMethod(request);
                }
                private void setRetyMethod(JsonObjectRequest request) {
                    try {
                        request.setRetryPolicy(new DefaultRetryPolicy(20000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    RequestQueue requestQueue = Volley.newRequestQueue(Mapforcalculation.this);
                    requestQueue.add(request);
                }
            protected void startLocationUpdates() {
                    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                }

                private void setLocationRequestMap() {
                   mLocationRequest = new LocationRequest();
                    mLocationRequest.setInterval(30000);
                    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                    mLocationRequest.setSmallestDisplacement(10);
             }
           private void getCurrentLocation() {
                    mGoogleMap.clear();
                    //Creating a location object
                    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                     location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                }
        private String getAddressbylatlong(double start_lat, double start_lon) {
                    Geocoder geocoder;
                    List<Address> addresses = null;
                    geocoder = new Geocoder(this, Locale.getDefault());
                    String address = null; // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                    String city = null;
                    String state = null;
         try {
                        // Here 1 represent max location result to returned, by documents it recommended 1 to 5
                        addresses = geocoder.getFromLocation(start_lat, start_lon, 1);
                        address = addresses.get(0).getAddressLine(0);
                        city = addresses.get(0).getLocality();
                        state = addresses.get(0).getAdminArea();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    String finalAddress;
                    try {
                        if (address != null) {
                            finalAddress = address.trim() + city.trim() + state.trim();
                            finalAddress = finalAddress.replace(" ", "");
                        } else {
                            return null;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                    return finalAddress;
                }
            @Override
                protected void onDestroy() {
                    super.onDestroy();
                    mGoogleApiClient.disconnect();
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
                }
            }

My service class is

    public class Serviceafterstartbutton extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    public static Boolean serviceRunning = false;
    double lat;
    double lng;
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private String vechi_id;
    private String drivi_ID;
    private String Rideid;
    private Location mYLocation;
    private Timer locTimwe;
    private Context appContext;
    private boolean tthreadnew=true;
    private int startId22;

    private ScheduledExecutorService executorService;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("onConn", "location");
//        Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();


        //Location Request

        buildGoogleApiClient();
        mGoogleApiClient.connect();


        Log.i("ongoogleapiinlstser", "null is false");

//        this.stopSelf();
    }

    protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();


    }

    public void createlocation() {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000); // Update location every second

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {

         startId22=startId;
        appContext=getBaseContext();//Get the context here


/*createlocation();*/
        serviceRunning = true;
        Rideid=intent.getStringExtra("Ride_id");

        final CarLoginSession carLoginSession = new CarLoginSession(getApplicationContext());
        final HashMap<String, String> car_hm = carLoginSession.isGetCarDetails();
        vechi_id = car_hm.get(CarLoginSession.IS_GET_VEHICLE_ID);

        //Driver login Session
        DriverLoginSession driverLoginSession = new DriverLoginSession(getApplicationContext());
        final HashMap<String, String> driv_hm = driverLoginSession.isGetDriverDetails();
        drivi_ID = driv_hm.get(DriverLoginSession.IS_DIV_ID);



        /*executorService = Executors.newScheduledThreadPool(4);
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                getCurrentLocation();
                update_aftr_strt(mYLocation);

                Log.i("ongoogleapi","thresds");
            }
        },10,5, TimeUnit.SECONDS);*/

        Log.d("onConn", "start_connected");
        return START_NOT_STICKY;
    }
    void showToast(final String text) {
        if (null != appContext) {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(appContext, ""+text, Toast.LENGTH_SHORT).show();
                }
            });

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

    class mythreadclass implements Runnable{
        int service_id;
        mythreadclass(int service_id){
            this.service_id=service_id;
        }

        @Override
        public void run() {
            synchronized (this){
                while (tthreadnew){
                    try {
                        getCurrentLocation();
                        Log.i("ongoogleapi","thresds");
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    private void getCurrentLocation() {


        //Creating a location object
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            mYLocation = location;
            update_aftr_strt(mYLocation);


            //moving the map to location

        }
    }


    private String getAddressbylatlong(double start_lat, double start_lon) {
        Geocoder geocoder;
        List<Address> addresses = null;
        geocoder = new Geocoder(this, Locale.getDefault());
        String address = null; // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = null;
        String state = null;

        try {
            // Here 1 represent max location result to returned, by documents it recommended 1 to 5
            addresses = geocoder.getFromLocation(start_lat, start_lon, 1);
            address = addresses.get(0).getAddressLine(0);
            city = addresses.get(0).getLocality();
            state = addresses.get(0).getAdminArea();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String finalAddress;
        try {
            if (address != null) {
                finalAddress = address.trim() + city.trim() + state.trim();
                finalAddress = finalAddress.replace(" ", "");
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return finalAddress;
    }

    private void update_aftr_strt(Location mYLocation) {

        double start_Lat=0;

        double start_lon=0;
        String addsres = null;
        try {
            start_Lat = mYLocation.getLatitude();
            start_lon = mYLocation.getLongitude();
            addsres = getAddressbylatlong(start_Lat, start_lon);


        } catch (Exception e) {
            e.printStackTrace();
//            getLocationMethods();
        }

        final String url = Api_url.url_link + "current_location_ride.php?latitude=" + start_Lat +
                "&longitude=" + start_lon + "&driverid=" + drivi_ID + "&loc_address=" + addsres + "&vehicle_id=" + vechi_id + "&ride_id=" + Rideid;
        Log.d("URL_Pcc", url);

        final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("after_Start_loc", response.toString());
                String aftr_atrt_respons = null;


                try {
                    aftr_atrt_respons = response.getString("update");
                    if (aftr_atrt_respons.equals("success")) {
                        showToast("updateaftr start");

                    } else {
                        showToast("update aftr start failed!!");                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

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

            }
        });
        setRetyMethod(request);
    }

    private void setRetyMethod(JsonObjectRequest request) {
        try {
            request.setRetryPolicy(new DefaultRetryPolicy(20000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestQueue requestQueue = Volley.newRequestQueue(Serviceafterstartbutton.this);
        requestQueue.add(request);
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Thread thread=new Thread(new mythreadclass(startId22));
        thread.start();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        tthreadnew =false;


    }
}

my error is:`

java.lang.OutOfMemoryError: Failed to allocate a 32 byte allocation with 8 free bytes and 8B until OO at java.lang.ProcessManager.exec(ProcessManager.java at java.lang.Runtime.exec(Runtime.java:174at java.lang.Runtime.exec(Runtime.java:247 at java.lang.Runtime.exec(Runtime.java:190) at java.lang.Daemons$FinalizerWatchdogDaemon.executeCommand(Daemons.java:341) at java.lang.Daemons$FinalizerWatchdogDaemon.run(Daemons.java:279) at java.lang.Thread.run(Thread.java:818)

`

lucky
  • 77
  • 9
  • you are using a lot of ur main UI thread, keep things on Thread. – W4R10CK Jan 18 '17 at 06:10
  • @W4R10CK thank you for ur answer......i am using these method only once in oncreate.the method which runs continuosly is written in service.can u explain me some more,please?i am new to development ...how to less use ui thread? – lucky Jan 18 '17 at 06:31

2 Answers2

0

//You can Create a radius for 100km and and just hide those markers if didnt lie in the 100km //

private void drawCircle(LatLng point){

            // Instantiating CircleOptions to draw a circle around the marker
            CircleOptions circleOptions = new CircleOptions();

            // Specifying the center of the circle
            circleOptions.center(point);

            // Radius of the circle
            circleOptions.radius(20);

            // Border color of the circle
            circleOptions.strokeColor(Color.BLACK);

            // Fill color of the circle
            circleOptions.fillColor(0x30ff0000);

            // Border width of the circle
            circleOptions.strokeWidth(2);

            // Adding the circle to the GoogleMap
            googleMap.addCircle(circleOptions);

        }

//Now calculate distance of patriclar latlong and and current position by this // // The computed distance is stored in results[0]. //If results has length 2 or greater, the initial bearing is stored in results[1]. //If results has length 3 or greater, the final bearing is stored in results[2].

float[] results = new float[1];

Location.distanceBetween(oldPosition.latitude, oldPosition.longitude, newPosition.latitude, newPosition.longitude, results);

//Check if the distance is greater than radius then show (>100km) Show on Map

0

You need to use thread inside the service as it run on main thread

your service can hang UI

remember the tasks that you need to perform one time should be called in oncreate method not onstartcommend method like

mGoogleApiClient.connect();

should be called in oncreate and don't use synchronized method in service

i have made few changes in your service class

you are not using location updates ( u always get last known location after thread wake up from sleep ( there is no need to create thread just for this we already have location updates, you will get user updates location

you are also not using updated location in your activity

Note: once your work is done you also need to stop this service as well.

public class Serviceafterstartbutton extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    public static Boolean serviceRunning = false;
    double lat;
    double lng;
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private String vechi_id;
    private String drivi_ID;
    private String Rideid;
    private Location mYLocation;
    private Timer locTimwe;
    private Context appContext;
    private boolean tthreadnew=true;
    private int startId22;

    private ScheduledExecutorService executorService;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("onConn", "location");
//        Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();


        //Location Request

        buildGoogleApiClient();

          startId22=startId;
        appContext=getBaseContext();//Get the context here


/*createlocation();*/
        serviceRunning = true;

        final CarLoginSession carLoginSession = new CarLoginSession(getApplicationContext());
        final HashMap<String, String> car_hm = carLoginSession.isGetCarDetails();
        vechi_id = car_hm.get(CarLoginSession.IS_GET_VEHICLE_ID);

        //Driver login Session
        DriverLoginSession driverLoginSession = new DriverLoginSession(getApplicationContext());
        final HashMap<String, String> driv_hm = driverLoginSession.isGetDriverDetails();
        drivi_ID = driv_hm.get(DriverLoginSession.IS_DIV_ID);

        mGoogleApiClient.connect();



        Log.i("ongoogleapiinlstser", "null is false");

//        this.stopSelf();
    }

    protected void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();


    }

    public void createlocation() {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000); // Update location every second

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {



        Rideid=intent.getStringExtra("Ride_id");

        /*executorService = Executors.newScheduledThreadPool(4);
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                getCurrentLocation();
                update_aftr_strt(mYLocation);

                Log.i("ongoogleapi","thresds");
            }
        },10,5, TimeUnit.SECONDS);*/

        Log.d("onConn", "start_connected");
        return START_NOT_STICKY;
    }
    void showToast(final String text) {
        if (null != appContext) {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(appContext, ""+text, Toast.LENGTH_SHORT).show();
                }
            });

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

    class mythreadclass implements Runnable{
        int service_id;
        mythreadclass(int service_id){
            this.service_id=service_id;
        }

        @Override
        public void run() {
            synchronized (this){
                while (tthreadnew){
                    try {
                        getCurrentLocation();
                        Log.i("ongoogleapi","thresds");
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    private void getCurrentLocation() {


        //Creating a location object
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            mYLocation = location;
            update_aftr_strt(mYLocation);


            //moving the map to location

        }
    }


    private String getAddressbylatlong(double start_lat, double start_lon) {
        Geocoder geocoder;
        List<Address> addresses = null;
        geocoder = new Geocoder(this, Locale.getDefault());
        String address = null; // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = null;
        String state = null;

        try {
            // Here 1 represent max location result to returned, by documents it recommended 1 to 5
            addresses = geocoder.getFromLocation(start_lat, start_lon, 1);
            address = addresses.get(0).getAddressLine(0);
            city = addresses.get(0).getLocality();
            state = addresses.get(0).getAdminArea();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String finalAddress;
        try {
            if (address != null) {
                finalAddress = address.trim() + city.trim() + state.trim();
                finalAddress = finalAddress.replace(" ", "");
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return finalAddress;
    }

    private void update_aftr_strt(Location mYLocation) {

        double start_Lat=0;

        double start_lon=0;
        String addsres = null;
        try {
            start_Lat = mYLocation.getLatitude();
            start_lon = mYLocation.getLongitude();
            addsres = getAddressbylatlong(start_Lat, start_lon);


        } catch (Exception e) {
            e.printStackTrace();
//            getLocationMethods();
        }

        final String url = Api_url.url_link + "current_location_ride.php?latitude=" + start_Lat +
                "&longitude=" + start_lon + "&driverid=" + drivi_ID + "&loc_address=" + addsres + "&vehicle_id=" + vechi_id + "&ride_id=" + Rideid;
        Log.d("URL_Pcc", url);

        final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("after_Start_loc", response.toString());
                String aftr_atrt_respons = null;


                try {
                    aftr_atrt_respons = response.getString("update");
                    if (aftr_atrt_respons.equals("success")) {
                        showToast("updateaftr start");

                    } else {
                        showToast("update aftr start failed!!");                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

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

            }
        });
        setRetyMethod(request);
    }

    private void setRetyMethod(JsonObjectRequest request) {
        try {
            request.setRetryPolicy(new DefaultRetryPolicy(20000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestQueue requestQueue = Volley.newRequestQueue(Serviceafterstartbutton.this);
        requestQueue.add(request);
    }

    @Override
    public void onLocationChanged(Location location) {


            mYLocation = location;
            update_aftr_strt(mYLocation);
    }

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


        // Thread thread=new Thread(new mythreadclass(startId22));
        // thread.start();

        // no need for this thread to create and put in sleep we already have location update that we will get after in every 10 seconds ( 10)

            createlocation();
            getCurrentLocation();

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        tthreadnew =false;


    }
}
Community
  • 1
  • 1
Adeel Javed
  • 372
  • 2
  • 11