How to send location of the device on server when needed

后端 未结 2 659
北海茫月
北海茫月 2020-11-30 03:47

I am developing a application in which i need current lat and long of the device. Time frame to get the lat/long will be decided by the server. Server will send notification

2条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 04:15

    Here is what i did.

    1. Fetch and store locations using the Google Play services fused location provider as described herehere

    2. I would avoid setting up a service instead you should trigger an alarm that requests for last available location. This further saves battery as the app does not go looking for a location vale but uses what other apps might have recently requested. In my opinion the received response is fairly accurate.. so do something like this

      public class LocationReceiver extends BroadcastReceiver {
      // Restart service every 30 seconds
      private static final long REPEAT_TIME = 1000 * 60 * 5;
      private static final long REPEAT_DAILY = 1000 * 60 * 60 * 24;
      @Override
      public void onReceive(Context context, Intent intent) 
      {
          Log.v("TEST", "Service loaded at start");
          AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
          Calendar cal = Calendar.getInstance();
          cal.add(Calendar.SECOND, 0);
      
          Intent i = new Intent(context, ServiceStartReceiver.class);
          PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
          service.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), REPEAT_TIME, pending);
      
      }
      }
      
    3. Since you have not mentioned that you want the updates in real time i think you can just dump all data in a temp sqlite database.

    4. Create a receiver to listen for changes in network and when over wifi simply send all data to your server. You can be a bit more smart while doing this by sending only when certain number of entries have accumulated or at a periodic interval.

    5. Alternatively the server can send a ping to the app via a GCM mnotification which can also trigger sending of data to your server.this is an amazing tutorial to describe sending GCM messages to the app.

    6. Finally some very interesting location strategies are mentioned here. You can pic when to trigger your location save based on user activity or some other context.

    Hope this helps.

提交回复
热议问题