【问题标题】:Send latitude and longitude to server every 5 minutes even the app was closed即使应用程序关闭,也每 5 分钟向服务器发送纬度和经度
【发布时间】:2016-05-05 09:50:17
【问题描述】:

我需要每 5 分钟向服务器发送一次纬度和经度值。我们的团队成员可以在旅行期间关闭此应用程序,同时将纬度和经度值发送到服务器。我不知道如何来实现这个方法。

【问题讨论】:

标签: android google-maps background


【解决方案1】:

我终于找到了我的问题的答案。我们可以在后台运行许多方法,如 Intent Service 和 Alarm Manager。我使用了后台进程的警报管理器。它会每 5 分钟调用一次服务。在我的MainActivity 中,我输入了下面提到的代码。

    private void scheduleNotify()
    {
    Intent notificationIntent = new Intent(this, SendLocation.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,0,1000*60*5,pendingIntent);
    }

AlarmManager,我设置了setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,0,1000*60*5,pendingIntent);

它将每 5 分钟重复一次持续时间(1000*60*5 毫秒 = 5 分钟)

SendLocation.class 
public class SendLocation extends BroadcastReceiver implements LocationListener {
 @Override
public void onReceive(Context mContext, Intent intent) {

    try {
        locationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);

        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled && !isNetworkEnabled) {

        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
         }

  }catch (Exception e){

    }

   Log.i("sendlocation","Every 5 minutes it will appear in Log Console"+latitude+" "+longitude);


  // code for send location to srver
  }

【讨论】:

  • 为了获得比位置管理器更好的性能切换到融合位置
猜你喜欢
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 2013-12-11
相关资源
最近更新 更多