nightcoder nightcoder - 1 year ago 69
SQL Question

How Can I Track a person using its location in Android

I am working on a project...I need to track a person using its Geo-location(latitude,longitude)..
- Person A's Location is updating on server in MYSQL DB when location become change.
- Person B need to see person A on Google-map through his/her own device (Android phone)


When I establish connection to server and try to get location from MYSQL DB ... connection become struck and App crashes.
Person B need to track until it reaches at a specific point.
Is there any other way to do this >??
Thanks for Helping in Advance

Downloading Tracking Location From Server

private class downloadTrackingLocationsAsync extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
protected String doInBackground(String... params) {
String ID = params[1];
HttpURLConnection conn = null;

try {
// create connection
URL wsURL=new URL(params[0]);
conn=(HttpURLConnection) wsURL.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

Uri.Builder builder = new Uri.Builder().appendQueryParameter("id", ID);
String data =;
byte[] outputInBytes = data.getBytes("UTF-8");
conn.setRequestProperty("Content-Length", "" + Integer.toString(outputInBytes.length));
OutputStream os = conn.getOutputStream();

//get data
InputStream bufferedInputStream = new BufferedInputStream(conn.getInputStream());
// converting InputStream into String
Scanner scanner = new Scanner(bufferedInputStream);
String strJSON = scanner.useDelimiter("\\A").next();
return strJSON;

} catch (MalformedURLException e) {
e.printStackTrace(); // URL is invalid
} catch (SocketTimeoutException e) {
e.printStackTrace(); // data retrieval or connection timed out
} catch (IOException e) {
e.printStackTrace(); // could not read response body
// (could not create input stream)
} finally {
if (conn != null) {conn.disconnect(); }
return null;
protected void onPostExecute(String result) {
if(result !=null) {
try {
JSONObject rootObject = new JSONObject(result);

double latitude = rootObject.optDouble("lattitude");
double longitude = rootObject.optDouble("longitude");

LatLng currentLocation = new LatLng(latitude, longitude);
Log.i("Location", currentLocation.toString());
Toast.makeText(context, "Tracking Location Downloaded", Toast.LENGTH_LONG).show();

}catch (JSONException e){
else {
Toast.makeText(context, "Result Null", Toast.LENGTH_SHORT).show();

I am Calling this Class using a function continuously

Answer Source

You should use AlarmManager and services and do it in background. For more details of AlarmManager refer this link

Update data from server at regular time intervals in background process using AlarmManager, BroadcastReceiver, Service and Notification Manager.

First Activate AlarmManager. Write below code in Activity class

public class MainActivity extends ListActivity {

     private static final long REPEAT_TIME = 1000 * 30;

        public void onCreate(Bundle savedInstanceState) {

        private void setRecurringAlarm(Context context) {

            Calendar updateTime = Calendar.getInstance();
            updateTime.set(Calendar.HOUR_OF_DAY, 12);
            updateTime.set(Calendar.MINUTE, 30);
            Intent downloader = new Intent(context, MyStartServiceReceiver.class);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, downloader,       PendingIntent.FLAG_CANCEL_CURRENT);

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

            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);

            Log.d("MyActivity", "Set alarmManager.setRepeating to: " + updateTime.getTime().toLocaleString());



First create BroadcastReceiver Class
public class MyStartServiceReceiver extends BroadcastReceiver { 
     public void onReceive(Context context, Intent intent) {
            Intent dailyUpdater = new Intent(context, MyService.class); 
            Log.d("AlarmReceiver", "Called context.startService from AlarmReceiver.onReceive");

When application is closed or is in background, periodically fetch data from server and show notification on status bar.

Create Service

public class MyService extends IntentService {
    public MyService() {
    protected void onHandleIntent(Intent intent) {
        Log.d("MyService", "About to execute MyTask");
        new MyTask().execute();
    private class MyTask extends AsyncTask<String, Void, Boolean> {
         protected Boolean doInBackground(String... strings) {
                Log.d("MyService - MyTask", "Calling doInBackground within MyTask");
               return false;
private void sendNotification(Context context) {
        Intent notificationIntent = new Intent(context, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        NotificationManager notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification =  new Notification(android.R.drawable.star_on, "Refresh", System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(context, "Title","Content", contentIntent);
        notificationMgr.notify(0, notification);

Don't forget write below lines in AndroidManifest.xml File

<service android:name="MyService" ></service> 
<receiver android:name="MyStartServiceReceiver" ></receiver>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download