0

I followed this to Get Location Coordinates For Every 10 Seconds

So Now Here I want to Change the Activity to Service So that I will start it as Background Service to Get Updates on Location for Every 10 Seconds...

But Here I modified UpdateUI() method

private void updateUI() {
    mLatitudeTextView.setText(String.format("%s: %f", mLatitudeLabel,
            mCurrentLocation.getLatitude()));
    mLongitudeTextView.setText(String.format("%s: %f", mLongitudeLabel,
            mCurrentLocation.getLongitude()));
    mLastUpdateTimeTextView.setText(String.format("%s: %s", mLastUpdateTimeLabel,
            mLastUpdateTime));
}

to

 private void updateUI() {

    try{
    mlatitude = String.valueOf(mCurrentLocation.getLatitude());
    mlongitude = String.valueOf(mCurrentLocation.getLongitude());
    }
    catch(Exception e){
        Toast.makeText(this,"Location Not Found",Toast.LENGTH_LONG).show();
    }
}

And I am Toasting those values at onStartCommand() and I have Given On start Command like this

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        buildGoogleApiClient();
        mRequestingLocationUpdates = true;
        updateUI();

        return mStartMode;  
}

But here it runs only for 1st time and it's not Displaying Values and it's not getting updates or not running for every 10 seconds.

However in Activity its working Fine I am getting Location Updates for every 10 seconds...

Can Anyone suggest how to Give the same in Service... so that I will get Updates

Update 1: To Run a Service for every 10 seconds I have added this...

private final Integer TEN_SECONDS = 10000;
    public void sendSendLocation() {
    new Handler().postDelayed(new Runnable() {
            public void run () {
                updateUI();
                new Handler().postDelayed(this, TEN_SECONDS);
            }
    },TEN_SECONDS);
}

But Here Location Displays Null... Can anyone suggest me...

Update 2:

Actually, I need to add updateValuesFromBundle(savedInstanceState) in OnStartCommand if I add it... the Service will work. But hence its a service I am Unable to Give Bundle savedInstanceState...

private void updateValuesFromBundle(Bundle savedInstanceState) {
        Log.i(TAG, "Updating values from bundle");
        if (savedInstanceState != null) {
            // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
            // the Start Updates and Stop Updates buttons are correctly enabled or disabled.
            if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
                mRequestingLocationUpdates = savedInstanceState.getBoolean(
                        REQUESTING_LOCATION_UPDATES_KEY);
                setButtonsEnabledState();
            }

            // Update the value of mCurrentLocation from the Bundle and update the UI to show the
            // correct latitude and longitude.
            if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
                // Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
                // is not null.
                mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
            }

            // Update the value of mLastUpdateTime from the Bundle and update the UI.
            if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
                mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
            }
            updateUI();
        }
    }

So I am Running UpdateUI() Directly at OnStartCommand() in service

Anyone Suggest me On this kind?

Whats Going On
  • 1,379
  • 6
  • 20
  • 49
  • @ MLN: Are you following above given link for service also? – Jitesh Mohite Mar 17 '18 at 12:10
  • Yes I am Using Entire Application Code In Github.. But I modified/Created MainActivity to service... I am Running new service and service Link of that code ... – Whats Going On Mar 19 '18 at 04:19
  • You can't get location frequently from a [background service on device with Android 8.0.](https://developer.android.com/about/versions/oreo/background-location-limits.html) – Thracian Mar 20 '18 at 22:14

3 Answers3

3

You can use handler or timertask.

Some of reported problems with TimerTask:

  • Can't update the UI thread
  • Memory leaks
  • Unreliable (doesn't always work)
  • Long running tasks can interfere with the next scheduled event

Handler:

 private final Integer TEN_SECONDS = 10000;
    public void sendSendLocation() {
    new Handler().postDelayed(new Runnable() {
            public void run () {
                updateUI();
                new Handler().postDelayed(this, TEN_SECONDS);
            }
    },TEN_SECONDS);
}
Whats Going On
  • 1,379
  • 6
  • 20
  • 49
  • I tried Your Code But Here Location is not Working... I think its not Updating Location... I need to think of it... – Whats Going On Mar 16 '18 at 05:40
  • new Handler().postDelayed(this, TEN_SECONDS); what this code doing inside handler? I guess we don't require that. – Jitesh Mohite Mar 17 '18 at 12:03
  • may Be its also required because when this service started It need some time to get Location Details.. like Address so I am using this but just 3 sec Delay – Whats Going On Mar 19 '18 at 09:30
  • @MLN is right. You can perhaps try a thread sleep, before starting the service. –  Mar 19 '18 at 11:30
  • Anonymous handlers are actually easiest way to leak Activity. Refrain doing this. Best way is to use static Handler class with weak reference to Activity. However, the problem with location update might be because location limits introduced Android 8.0 if you are using a device with Android 8.0 and above – Thracian Mar 20 '18 at 22:24
1

Try this code

private void startProcess(){
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
          updateUI();  
        }
    }, 0, 10000);
}

This startProcess method write in startCommand method

  • I am Getting This Exception `java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()` after adding Your Code – Whats Going On Mar 16 '18 at 05:29
1

Follow this..... your code is correct but onConnected() is not used... if your are using it in service.. you must add this line...... In Your Code you can Use googleApiclient.connect();

So in your code

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect(); **// Add this line**
    createLocationRequest();
}

You missing this I also faced same problem but after adding this its worked for me background service...

ravi
  • 474
  • 1
  • 3
  • 11