2017-11-01 5 views
0

사용자가 한 곳에서 다른 곳으로 이동할 때 위치를 서버로 업데이트해야합니다. 내 앱이 열릴 때 업데이트 할 수 있습니다. 사용자가 오랫동안 앱을 열지 않아도 위치를 업데이트하려면 어떻게해야합니까?응용 프로그램이 열려 있지 않아도 서버에 위치를 업데이트하는 방법

+1

위치 클래스와 함께 GCM 네트워크 관리자 또는 Firebase 작업 스케줄러를 사용해보십시오. – param

답변

0

서비스를 이용하십시오.

public class MyService extends Service implements LocationListener, 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener { 
private static final String TAG = "MyService"; 
private static final int UPDATE_INTERVAL = 5000; 
private static final int FASTEST_INTERVAL = 3000; 
private GoogleApiClient client; 
private LocationRequest locationRequest; 
private String lat, lon; 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1) { 
    if (ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) == 
PackageManager.PERMISSION_GRANTED && 
ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_COARSE_LOCATION) == 
PackageManager.PERMISSION_GRANTED) { 
      LocationServices.FusedLocationApi.requestLocationUpdates(client, 
locationRequest, this); 
     } 
    }else { 
     LocationServices.FusedLocationApi.requestLocationUpdates(client, 
locationRequest, this); 
    } 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

@Override 
public void onLocationChanged(Location location) { 
    Log.i(TAG, "onLocationChanged: " + location); 
    lat = String.valueOf(location.getLatitude()); 
    lon = String.valueOf(location.getLongitude()); 

    updateLocation(); 

} 


@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.d(TAG, "onStartCommand"); 
    super.onStartCommand(intent, flags, startId); 
    return START_STICKY; 
} 

@Override 
public void onCreate() { 
    Log.d(TAG, "onCreate"); 
    preferences = getSharedPreferences(AppConfig.PREF, MODE_PRIVATE); 
    locationRequest = new LocationRequest(); 
    locationRequest.setInterval(UPDATE_INTERVAL); 
    locationRequest.setFastestInterval(FASTEST_INTERVAL); 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

    buildGoogleApiClient(); 


} 

protected synchronized void buildGoogleApiClient() { 
    client = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
    client.connect(); 
} 

@Override 
public void onDestroy() //remove location update 
{ 
    Log.d(TAG, "onDestroy"); 
    super.onDestroy(); 

    if (client != null) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(client, this); 
     client.disconnect(); 
    } 


} 


private void updateLocation(){ 

    StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOCATIONUPDATE, new Response.Listener<String>() { 
     @Override 
     public void onResponse(String response) { 
      Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show(); 

    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show(); 
     } 
    }) { 
     protected Map<String, String> getParams() { 
      Map<String, String> params = new HashMap<>(); 
      params.put("currLat",lat); 
      params.put("currLon",lon); 
      return params; 
     } 
    }; 
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); 
    requestQueue.add(stringRequest); 
} 
} 

귀하의 활동에서이 서비스를 호출하십시오.

Intent serviceIntent = new Intent(this, MyService.class); 
startService(serviceIntent);