即使应用程序已关闭,也会每5分钟向服务器发送经度和纬度

时间:2016-01-28 06:37:13

标签: android google-maps background

我需要每隔5分钟向服务器发送纬度和经度值。我们的团队成员可以在旅行期间关闭此应用程序,此时纬度和经度值也会发送到服务器。我没有想法如何实现这个方法。

1 个答案:

答案 0 :(得分:2)

最后我找到了我的问题的答案。我们可以运行后台进程许多方法,如Intent Service和Alarm Manager。我使用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 ms = 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
  }