2014-10-08 7 views
0

현재 사용자 위치를 얻으려고했습니다. 나는 GPS를 켜고 응용 프로그램을 시작합니다. 모든게 괜찮을 것 같습니다, 나는 현재 사용자 위치를 얻을 수 있습니다.GPS가 꺼진 상태에서도 onLocationChanged가 호출됩니다.

문제는 GPS를 끄고 응용 프로그램을 실행할 때입니다. onLocationChanged가 호출됩니다. GPS를 끄고 호출해야합니까? 그렇다면 왜?

package company.com.locationservicesapi; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.provider.Settings; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.TextView; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; 
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; 
import com.google.android.gms.common.api.PendingResult; 
import com.google.android.gms.common.api.Status; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 

public class LocationServicesAPIActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener { 
    private static final String TAG = "Location Service API"; 
    GoogleApiClient googleApiClient; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
     if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
      Log.i(TAG, "GPS turned on"); 
     } else { 
      Log.i(TAG, "GPS turned off"); 
     } 

     setContentView(R.layout.activity_location_services_api); 
     int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
     if (result == ConnectionResult.SUCCESS) { 
      googleApiClient = new GoogleApiClient.Builder(this) 
        .addApi(LocationServices.API) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .build(); 
      googleApiClient.connect(); 
     } else { 
      GooglePlayServicesUtil.getErrorDialog(result, this, 1).show(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.location_services_api, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     Log.d(TAG, "Connected"); 
     LocationRequest locationRequest = LocationRequest.create() 
       .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
       .setInterval(1000) 
       .setNumUpdates(1); 

     LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); 
    } 

    public void onLocationChanged(Location location) { 
     Log.d(TAG, "Location Changed"); 
     TextView textView = (TextView) findViewById(R.id.textViewLocation); 
     textView.setText('@' + location.getLatitude() + "," + location.getLongitude()); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     Log.d(TAG, "Connection Suspended"); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     Log.d(TAG, "Connection Failed"); 
    } 
} 

activity_location_services_api.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".LocationServicesAPIActivity"> 

    <TextView 
     android:id="@+id/textViewLocation" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 

</RelativeLayout> 

의 AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="company.com.locationservicesapi"> 

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme"> 
     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 

     <activity 
      android:name=".LocationServicesAPIActivity" 
      android:label="@string/app_name"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

로그 캣의 출력 : FusedLocationApi 그냥을

10-08 14:18:34.242 4208-4208/company.com.locationservicesapi I/Location Service API﹕ GPS turned off 
10-08 14:18:34.625 4208-4208/company.com.locationservicesapi D/Location Service API﹕ Connected 
10-08 14:18:35.765 4208-4208/company.com.locationservicesapi D/Location Service API﹕ Location Changed 
+0

확실하지 도움이되기를 바랍니다 public void onConnectionFailed(ConnectionResult connectionResult)

locationManager.removeUpdates(this); this.locationManager = null; 

를 넣어,하지만 당신은 셀 네트워크에서 위치를 검색 할 수 있습니다. 정확하지는 않지만, 거친 위치와 정밀한 위치 모두에 대한 권한을 포함하고 있기 때문에 거기에서 가져올 수 있습니다. – dharms

+0

"android.permission.ACCESS_FINE_LOCATION"만있는 경우 위에서 설명한 동일한 동작을 제공합니다. "android.permission.ACCESS_COARSE_LOCATION"만있는 경우 응용 프로그램이 "java.lang.SecurityException : Provider gps ACCESS_FINE_LOCATION 권한이 필요합니다"라는 예외와 충돌합니다. –

답변

0

를 호출하지 않습니다 유효한 GPS 신호를 사용할 수있는 경우. WFPS, Cell-ID 및 Sensors를 사용하여 유효한 위치를 얻습니다. 그것이 FusedLocationApi의 모든 것입니다 : 기기의 모든 가능성을 사용하여 가장 정확한 위치를 사용하십시오.

단지 GPS 신호를 듣고 싶다면 LocationManager.GPS_PROVIDER 플래그를 사용하여 LocationManager을 공급자로 사용하는 것입니다.

+0

더 이상 사용되지 않습니까? 내가 놓친 것을 놓치지 않았다면, 현재 API가 Google Play 서비스에 있음을 읽었습니다. –

+1

LocationManager가 아니기 때문에 AFAICT는 더 이상 사용되지 않습니다. FusedLocationApi는 LocationManager의 래퍼 일뿐입니다 (LocationClient는 이전에 사용되지 않았으므로 사용되지 않습니다). –

0

내 매니페스트 안에 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />이 있으므로 대략적인 위치에 액세스하려면 네트워크를 사용합니다. android manifest description

당신은 아무런 연결이 없을 때마다 위치 업데이트를 제거 할 수 있습니다. 단지 처음 private LocationManager locationManager;을 선언하고 난 이러한 경우이