Search code examples
androidhandlerlocationlistener

Will it drain the phone's battery if I use a Handler to request location every several seconds?


I'm making an app that silences the user's ringer based on their location. I have a Service that runs in the background, and I need it to get the user's location every few seconds. I'm using LocationListener, so I tried putting onLocationChanged inside my service's onStart method, but I was not allowed. So, I'm wondering if I used a Handler to request the user's location every 5 seconds, if it would drain their battery. I'm doing this because I cannot test the app by moving around, so I'm not sure if onLocationChanged gets called.

public class myService extends Service implements LocationListener {
Double lat;
Double lng;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Let it continue running until it is stopped.
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();





    return START_STICKY;

}

@Override
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

}



@Override
public void onLocationChanged(Location location) {

    if (MainActivity.location != null) {


       lat = MainActivity.location.getLatitude();

        lng = MainActivity.location.getLongitude();


        if (MainActivity.placeArrayList.size() != 0) {
            for (int i = 0; i < MainActivity.placeArrayList.size(); i++) {


                Log.e("hello", String.valueOf(Float.parseFloat(MainActivity.latitudeArrayList.get(i))));

                MainActivity.destination.setLatitude(Double.parseDouble(MainActivity.latitudeArrayList.get(i)));
                MainActivity.destination.setLongitude(Double.parseDouble(MainActivity.longitudeArrayList.get(i)));
                Log.e("distancemeters", String.valueOf(MainActivity.location.distanceTo(MainActivity.destination)));

                if (MainActivity.location.distanceTo(MainActivity.destination)<100) {




                    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

                    audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);


                } else {



                }

            }


        }
    }

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

Solution

  • This is not how you should get user location. Try like this. If you want to test you function use Android Emulator + Android Device Monitor. There you can set and change user location.