2016-10-08 3 views
4

ユーザーの所在地を取得し、API < 23で正常に動作するコードを書くことができます。ただし、API 23以降では、ログに何も返されません。アンドロイドAPIでユーザーの位置を取得する23

詳細:
デバイスのGPSを手動で有効にします。 最初の実行では、アプリのリクエストの許可とログの返されません。
次回は、私の用意したToast(あなたのプロバイダをチェックしてください)を返します。

これは私の書いたコードです:

public class MainActivity extends AppCompatActivity implements LocationListener { 

private static final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 124; 
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 123; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Here, thisActivity is the current activity 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_FINE_LOCATION)) { 

     } else { 

      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_FINE_LOCATION); 
     } 
    } 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_COARSE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_COARSE_LOCATION)) { 

     } else { 
      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_COARSE_LOCATION); 

     } 
    } 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    String provider = locationManager.getBestProvider(new Criteria(), false); 
    Location location = locationManager.getLastKnownLocation(provider); 
    if (location == null) { 
     Toast.makeText(this, "Check your provider", Toast.LENGTH_SHORT).show(); 
    } else { 
     Log.i("New Location", "lat: " + location.getLatitude()); 
     Log.i("New Location", "lng: " + location.getLongitude()); 
    } 
} 

@Override 
public void onLocationChanged(Location location) { 
    Log.i("Location", "lat: " + location.getLatitude()); 
    Log.i("Location", "lng: " + location.getLongitude()); 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 

}のAndroid APIで

+0

あなたのメソッド 'getBestProvider()'では有効なプロバイダのみをチェックし、プロバイダが有効でない場合は、場所は常に** null **を返します。 この場合、プロバイダが有効かどうかをチェックし、無効になっている場合は有効にします。 – AndroidHacker

+0

私は真に偽に変更しましたが、解決しませんでした。 2番目の方法は?私はほとんど新しいアンドロイドです。 –

答えて

5

は23+ android.permission.ACCESS_FINE_LOCATIONandroid.permission.ACCESS_COARSE_LOCATIONの場合that's、 "危険" とみなさ権限を処理するための新しい方法がありますとりわけ、

すでにandroid.permission.ACCESS_FINE_LOCATIONを使用している場合は、android.permission.ACCESS_COARSE_LOCATIONを処理する必要はありません。

このリンクは、Android API 23以降で実行時に権限を処理する方法を示す公式ドキュメントからご覧ください。

https://developer.android.com/training/permissions/requesting.html

この1つはまた、あなたを助けるかもしれません。権限をチェックする方法

https://developer.android.com/guide/topics/location/strategies.html

:あなたは、実行時にパーミッションを要求してもあなたはまだしなければならないこと

if (ContextCompat.checkSelfPermission(thisActivity, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
    != PackageManager.PERMISSION_GRANTED) { 

    // Should we show an explanation? 
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, 
     Manifest.permission.ACCESS_FINE_LOCATION)) { 

     // Show an expanation to the user *asynchronously* -- don't block 
     // this thread waiting for the user's response! After the user 
     // sees the explanation, try again to request the permission. 

    } else { 

     // No explanation needed, we can request the permission. 

     ActivityCompat.requestPermissions(thisActivity, 
      new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
      MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); 

     // MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION is an 
     // app-defined int constant. The callback method gets the 
     // result of the request. 
    } 
} 

注:権限を要求する方法

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, 
    Manifest.permission.ACCESS_FINE_LOCATION); 

次のようにアンドロイドマニフェストのパーミッションを保持してください:

<manifest ... > 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    ... 
    <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. --> 
    <uses-feature android:name="android.hardware.location.gps" /> 
    ... 
</manifest> 

権限を確認して付与した後、上記の場所戦略のリンクを確認すると、見つからないものの詳細が表示されます。

基本的には、ロケーション更新を受信するためにリスナーを登録していません。 onCreate()メソッドの最後にこの行を追加したら、ログに場所の更新が表示されるはずです。

// Register the listener with the Location Manager to receive location updates 
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 
+0

は問題を解決しませんでした。私は問題が許可されていないと思う。トーストをもう一度返すので。 Toastは "location == null"のときになります。 –

+0

更新された回答を確認してください。あなたは今すぐ行くべきです。 –

+0

ありがとうございます。あなたの答えは問題を解決しました。しかし、それはload locationUpdateメソッドを実行します(ちょっとした方法)。 onCreateの私の位置ゲッターは場所を取得しません(私の準備トーストを返します)。それのための解決策ではありませんか?またはこれらの行を削除しますか? –

関連する問題