11

I have to send my current location details (lat & long) to server periodically (Ex: for every 5 minutes). Is there any best way? I know how to get the current location & how to send the details to server. But how do I repeat this in periodic intervals?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Santhosh
  • 4,956
  • 12
  • 62
  • 90
  • 1
    Please check this out ,much similar app and is working fine but i need some help regarding some features which you will know after reading my post , and sorry for putting this thing in answer as i can,t find the option of comment. . http://stackoverflow.com/questions/14088095/how-can-i-send-the-gps-and-network-location-cordinates-to-a-server-static-ip/14103445#14103445 – user2010282 Jan 04 '13 at 12:02

5 Answers5

11

Register an alarm using AlarmManager to wake up after 5min when user open the application first time. create a service(fetch location and update to server) to run when alarm notifies your application. After the service finished the work , register for an alarm again to wake up after 5min. by this way you can achieve your task.

ref

Android: How to periodically send location to a server

http://developer.android.com/reference/android/app/AlarmManager.html

http://developer.android.com/reference/android/app/Service.html

1st Edit - Adding code sample

Step 1 - Create alarm manager and register alarm

AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(Main.this, YourWakefulReceiver.class);
bool flag = (PendingIntent.getBroadcast(Main.this, 0,
                intent, PendingIntent.FLAG_NO_CREATE)==null);
/*Register alarm if not registered already*/
if(flag){
PendingIntent alarmIntent = PendingIntent.getBroadcast(Main.this, 0,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Create Calendar obj called calendar
        Calendar calendar = Calendar.getInstance();

/* Setting alarm for every one hour from the current time.*/
int intervalTimeMillis = 1000 * 60 * 60; // 1 hour 
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), intervalTimeMillis,
                        alarmIntent);
}

Step 2 - Create Receiver class

public class YourWakefulReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            Intent service = new Intent(context, SimpleWakefulService.class);
            startWakefulService(context, service);
        }
    }
}

Setp 3 - Create Service class

public class SimpleWakefulService extends IntentService {

    private static String tagName = "YourService";

    public SimpleWakefulService() {
        super("YourService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Start your location
        LocationUtil.startLocationListener();
        try {
        // Wait for 10 seconds
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
        }
        //Stop location listener
        LocationUtil.stopLocationListener();
        // upload or save location
        uploadGps();

        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

}

Step 4 - Register service and receiver

<service android:name="com.envision.ghari.services.SimpleWakefulService"></service>
        <receiver android:name="com.envision.ghari.receivers.YourWakefulReceiver"></receiver>

Note : This code is to understand the implementation. It will not compile.

Amir Dora.
  • 2,831
  • 4
  • 40
  • 61
abbas.aniefa
  • 2,855
  • 21
  • 30
2

Using BroadcastReceiver is a good choice for sending periodic requests.

Here is a tutorial to use BroadcastReceiver.

Jack
  • 223
  • 3
  • 13
ngesh
  • 13,398
  • 4
  • 44
  • 60
1

Best way to wakeup the service using the AlarmManager and post the location you get to the server.

Dharmendra
  • 33,296
  • 22
  • 86
  • 129
0

As it does not require UI interaction you should create a service for this, service will invoke requestLocationUpdates method, in this method, pass parameter minimum time to 5 mins.

jeet
  • 29,001
  • 6
  • 52
  • 53
-1

I am developing an application that gets position of the cell phone all day long in 10 and 15 seconds in a service, it works fine but sometimes the method OnLocationChanged of the Network provider listener stop to being called.

 import android.location.Address;
    import android.location.Geocoder;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    import android.widget.TextView;


    import java.io.IOException;
    import java.util.List;

    import foodinn.databases.LocationUpdaterDatabase;

    public class LocationUpdatesActivity extends AppCompatActivity {
        private LocationUpdaterDatabase locationUpdaterDatabase;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_location_updates);

            locationUpdaterDatabase = new LocationUpdaterDatabase(this, "Locations.db", null, 1);

            final Geocoder geocoder = new Geocoder(this);

            ListView listView = (ListView) findViewById(R.id.locationUpdatesListView);

            listView.setAdapter(new SimpleCursorAdapter(this, R.layout.location_updates_list_view_view, locationUpdaterDatabase.getLocationUpdates(), new String[] {"latitude", "longitude", "whenUpdated"}, new int[] {R.id.listViewTextView1, R.id.listViewTextView2, R.id.listViewTextView3}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER));

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    double latitude = Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView1)).getText().toString());
                    double longitude = Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView2)).getText().toString());

                    try {
                        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);

                        String address = addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                        String city = addressList.get(0).getLocality();
                        String state = addressList.get(0).getAdminArea();
                        String country = addressList.get(0).getCountryName();
                        String postalCode = addressList.get(0).getPostalCode();
                        String knownName = addressList.get(0).getFeatureName();

                        ((TextView) view.findViewById(R.id.listViewTextView4)).setText(address + ", " + city + ", " + country);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
Vicky Mahale
  • 1,209
  • 11
  • 18
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – J. Chomel Jan 19 '17 at 15:12