2016-09-18 2 views
0

저는 Windows 애플리케이션 프로그래머이며 최근에 Android를 배우기 시작했습니다. 나는 "시작"버튼을 클릭 한 후 매 30 초마다 GPS 좌표를 주기적으로 알려주고 "중지"버튼 (데이터를 받아들이는 웹 서비스를 이미 개발했다)을 클릭하여 중지하는 앱을 만들 계획이다. 창에서 나는 타이머를 사용할 것이고 모든 "진드기"에 GPS 좌표를 찾아 보낼 것이다. 안드로이드에서 비슷한 일이 어떻게 이루어지는 지 이해하는 데 도움을주십시오.주기적으로 GPS 좌표를 보냅니다.

답변

0

난 내 응용 프로그램에서 사용하고 있는데 그 작업 perfect.I'm 몇 단계를 따르십시오 업데이트 위치 융합 API를 사용하는 방법을 확인하시기 바랍니다.

1 단계 메이크업이 클래스 GoogleLocationService.java

public class GoogleLocationService { 
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks(); 
LocationUpdateListener locationUpdateListener; 
Context activity; 
protected GoogleApiClient mGoogleApiClient; 
protected LocationRequest mLocationRequest; 

public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000; 


public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) { 
    this.locationUpdateListener = locationUpdateListener; 
    this.activity = activity; 
    buildGoogleApiClient(); 
} 

protected synchronized void buildGoogleApiClient() { 
    //Log.i(TAG, "Building GoogleApiClient"); 
    mGoogleApiClient = new GoogleApiClient.Builder(activity) 
      .addConnectionCallbacks(callbacks) 
      .addOnConnectionFailedListener(callbacks) 
      .addApi(LocationServices.API) 
      .build(); 
    createLocationRequest(); 
    mGoogleApiClient.connect(); 
} 

protected void createLocationRequest() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

} 

private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

    @Override 
    public void onConnected(Bundle bundle) { 
     startLocationUpdates(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     mGoogleApiClient.connect(); 
    } 

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

     if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) { 
      Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show(); 

     } 
     locationUpdateListener.cannotReceiveLocationUpdates(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     if (location.hasAccuracy()) { 
      if (location.getAccuracy() < 30) { 
       locationUpdateListener.updateLocation(location); 
      } 
     } 
    } 
} 

private static boolean locationEnabled(Context context) { 
    boolean gps_enabled = false; 
    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
    try { 
     gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
    return gps_enabled; 
} 

private boolean servicesConnected(Context context) { 
    return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context); 
} 

private boolean isPackageInstalled(String packagename, Context context) { 
    PackageManager pm = context.getPackageManager(); 
    try { 
     pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); 
     return true; 
    } catch (PackageManager.NameNotFoundException e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 


public void startUpdates() { 
    /* 
    * Connect the client. Don't re-start any requests here; instead, wait 
    * for onResume() 
    */ 
    if (servicesConnected(activity)) { 
     if (locationEnabled(activity)) { 
      locationUpdateListener.canReceiveLocationUpdates(); 
      startLocationUpdates(); 
     } else { 
      locationUpdateListener.cannotReceiveLocationUpdates(); 
      Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show(); 
     } 
    } else { 
     locationUpdateListener.cannotReceiveLocationUpdates(); 
     Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show(); 
    } 
} 

//stop location updates 
public void stopUpdates() { 
    stopLocationUpdates(); 
} 

//start location updates 
private void startLocationUpdates() { 

    if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     return; 
    } 
    if (mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks); 
    } 
} 

public void stopLocationUpdates() { 
    if (mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks); 
    } 
} 

public void startGoogleApi() { 
    mGoogleApiClient.connect(); 
} 

public void closeGoogleApi() { 
    mGoogleApiClient.disconnect(); 
} 

} 

2 단계. 이 인터페이스 LocationUpdateListener.java

public interface LocationUpdateListener { 

/** 
* Called immediately the service starts if the service can obtain location 
*/ 
void canReceiveLocationUpdates(); 

/** 
* Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and 
*/ 
void cannotReceiveLocationUpdates(); 

/** 
* Called whenever the location has changed (at least non-trivially) 
* @param location 
*/ 
void updateLocation(Location location); 

/** 
* Called when GoogleLocationServices detects that the device has moved to a new location. 
* @param localityName The name of the locality (somewhere below street but above area). 
*/ 
void updateLocationName(String localityName, Location location); 
} 

단계 당신의 한 OnCreate

개인 GoogleLocationService googleLocationService 3. 호출이 확인;

googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() { 
    @Override 
    public void canReceiveLocationUpdates() { 
    } 

    @Override 
    public void cannotReceiveLocationUpdates() { 
    } 

    //update location to our servers for tracking purpose 
    @Override 
    public void updateLocation(Location location) { 
     if (location != null) { 
      Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude()); 

     } 
    } 

    @Override 
    public void updateLocationName(String localityName, Location location) { 

     googleLocationService.stopLocationUpdates(); 
    } 
}); 
googleLocationService.startUpdates(); 


and call this onDestroy 
if (googleLocationService != null) { 
    googleLocationService.stopLocationUpdates(); 
} 

희망이 당신의 문제를 해결하는 데 도움이 될 것입니다.

+0

어디에서 실제로 시작하고 멈 춥니 까? –

+0

3 단계에서 볼 수 있습니까? – Saveen

+0

Windows XNA에서는 타이밍에 따라 작동하지만 안드로이드에서는 알람 관리자를 사용해야합니다. 그것을 확인하십시오 . –

0

RxGpsService (RxJava를 사용하여 GPS 위치 및 경로 통계를 검색하는 Android 서비스)를 살펴보십시오. 현재 속도, 거리, 경과 시간 및 중간 지점이 포함 된 RouteStats 개체를 검색합니다. 또한 크로노가 멈추었을 때 위치를 버리기 위해 크로노를 재생/정지 할 수 있습니다.

관련 문제