2016-06-29 2 views
0

나는 백그라운드에서 사용자 위치를 가져오고 위도와 경도가있는 활동에 브로드 캐스트를 보내는 LocationService를 보유하고 있습니다. 이 질문에 대한 답변으로 표시된 코드는 Background service with location listener in android위치 서비스를 사용하여 Google지도 업데이트

입니다. Android Studio에서 제공하는 Google지도 활동으로 프로젝트를 만들었습니다. MapsActivity에서 나는 지금 새 위치와지도를 업데이트하려면이

public class newMessage extends BroadcastReceiver { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (action.equalsIgnoreCase(LocationService.BROADCAST_ACTION)) { 
       Bundle extra = intent.getExtras(); 
       latitude = extra.getDouble("Latitude"); 
       longitude = extra.getDouble("Longitude"); 

       System.out.println("Latitude: "+latitude); 
       System.out.println("Longitude: "+longitude); 

       LatLng newLocation = new LatLng(latitude,longitude); 
      } 
     } 
    } 

같은 방송 엑스트라를 얻을하지만 난 어떻게하는지 모르겠어요. 현재 설정으로 가능합니까?

답변

1

활동에 방송 수신기를 선언하고

public BroadcastReceiver locationUpdateReceiver = new BroadcastReceiver(){ 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      //show current location marker 
mMap.addMarker(new MarkerOptions().position(/*your lat long*/).title("My Location"))); 
     } 
    }; 
+0

정확히 내가 필요한 것! 고마워. – Jaimy

1

현재 위치를 얻을 수있는 위치 서비스를 만들어야합니다. 이 예를 확인하십시오 :

public class LocationService extends Service implements 
     LocationListener, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener { 

    private static final String TAG = LocationService.class.getSimpleName(); 
    protected GoogleApiClient mGoogleApiClient; 
    protected LocationRequest mLocationRequest; 
    protected Location mCurrentLocation; 

    @Override 
    public void onCreate() { 

    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     buildGoogleApiClient(); 
     mGoogleApiClient.connect(); 
     return START_NOT_STICKY; 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     Log.i("fixedrec", TAG + ">Connected to GoogleApiClient"); 
     if (mCurrentLocation == null) { 
      mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
      mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); 
     } 
     startLocationUpdates(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 


    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     mGoogleApiClient.disconnect(); 
     Log.d("fixedrec", TAG+ ">StoppingService"); 
     mNM.cancel(NOTIFICATION); 
     stopForeground(true); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     //plase where you get your locations 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     Log.d("fixedrec", TAG + "> Connection failed: ConnectionResult.getErrorCode() = " 
       + connectionResult.getErrorCode()); 
    } 

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

    protected void startLocationUpdates() { 
     LocationServices.FusedLocationApi.requestLocationUpdates(
       mGoogleApiClient, mLocationRequest, this); 
     Log.i("fixedrec", TAG + "> StartLocationUpdates"); 
    } 


    protected synchronized void buildGoogleApiClient() { 
     Log.i("fixedrec", TAG + "> Building GoogleApiClient"); 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(10000); 
     mLocationRequest.setFastestInterval(5000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    } 
} 

응용 프로그램에서 위치를 브로드 캐스트하려면 OtCast와 같은 BroadCastReceiver 또는 EventBus를 사용할 수 있습니다. 그런 다음 googleMap을 만들고 여기에 가져온 마커를 추가하십시오. 당신이> = 23

는 또한이 프로젝트를 연구 할 수 SDK를 처리하는 경우

는 매니페스트 파일 내부 코드 안에 요 쓰기 locationPermissions을 잊지 마십시오. Fixedrec3

필요한 모든 것이 있습니다.

+0

덕분에 현재 위치에 마커를 보여! 프로젝트를 살펴 보겠습니다. 나는 이미 위치 서비스를 가지고 있으며, 방송을 사용하여 활동 위치를 전송하므로 어떤 일이 잘못 될지 알 수 없습니다. 그러나이 프로젝트는 나에게 올바른 방향으로 추진력을 줄 수 있습니다. – Jaimy

+0

컴파일하고 내용을 확인하십시오. 그런 다음 프로젝트 내에서 코드를 복사하여 붙여 넣어 작업을 수행 할 수 있습니다. BroadCastReciever 사용을 피하십시오 - 복잡합니다. 대신 otto를 사용하십시오. –

+0

BroadcastRiveriver를 사용해야합니다. 그것은 학교 프로젝트의 요구 사항입니다. 하지만 지금은 제대로 작동하고 있습니다. 당신의 도움을 주셔서 감사합니다. 확실히 Fixedrec3 프로젝트와 오토를 살펴볼 것입니다! – Jaimy

관련 문제