Skip to content Skip to sidebar Skip to footer

Send Current Location To Server Periodically In Android

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 & ho

Solution 1:

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

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

Intentintent=newIntent(Main.this, YourWakefulReceiver.class);
boolflag= (PendingIntent.getBroadcast(Main.this, 0,
                intent, PendingIntent.FLAG_NO_CREATE)==null);
/*Register alarm if not registered already*/if(flag){
PendingIntentalarmIntent= PendingIntent.getBroadcast(Main.this, 0,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

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

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

Step 2 - Create Receiver class

publicclassYourWakefulReceiverextendsWakefulBroadcastReceiver {

    @OverridepublicvoidonReceive(Context context, Intent intent) {
            Intentservice=newIntent(context, SimpleWakefulService.class);
            startWakefulService(context, service);
        }
    }
}

Setp 3 - Create Service class

publicclassSimpleWakefulServiceextendsIntentService {

    privatestaticStringtagName="YourService";

    publicSimpleWakefulService() {
        super("YourService");
    }

    @OverrideprotectedvoidonHandleIntent(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

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

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

Solution 2:

Using BroadcastReceiver is a good choice for sending periodic requests.

Here is a tutorial to use BroadcastReceiver.

Solution 3:

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

Solution 4:

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.

Solution 5:

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;

    publicclassLocationUpdatesActivityextendsAppCompatActivity {
        private LocationUpdaterDatabase locationUpdaterDatabase;

        @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_location_updates);

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

            finalGeocodergeocoder=newGeocoder(this);

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

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

            listView.setOnItemClickListener(newAdapterView.OnItemClickListener() {
                @OverridepublicvoidonItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    doublelatitude= Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView1)).getText().toString());
                    doublelongitude= Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView2)).getText().toString());

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

                        Stringaddress= addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()Stringcity= addressList.get(0).getLocality();
                        Stringstate= addressList.get(0).getAdminArea();
                        Stringcountry= addressList.get(0).getCountryName();
                        StringpostalCode= addressList.get(0).getPostalCode();
                        StringknownName= addressList.get(0).getFeatureName();

                        ((TextView) view.findViewById(R.id.listViewTextView4)).setText(address + ", " + city + ", " + country);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

Post a Comment for "Send Current Location To Server Periodically In Android"