2017-03-23 17 views
0

である私は、このチュートリアルを経由してAndroidの中の位置情報サービスを学んでいます:https://www.youtube.com/watch?v=nwdwzQhutdo場所は常にnull

私はビデオに基づいて、すべての権利のコードを持っていますが、場所は常にnullです。私はそれがなぜ起こっているのか理解できないようです。

OUTPUT:Location could not be detected. Try again later.

CODE

public void onCreate() { 
    getLocation(); 
    locationButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      if (null != mGoogleApiClient && mGoogleApiClient.isConnected()) { 
       try { 
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
        if (location != null) { 
         Toast toast = Toast.makeText(getApplicationContext(), Double.toString(location.getLatitude()), Toast.LENGTH_SHORT); 
         toast.show(); 
        } else { 
         Toast toast = Toast.makeText(getApplicationContext(), "Location could not be detected. Try again later.", Toast.LENGTH_SHORT); 
         toast.show(); 
        } 
       } catch(SecurityException e) { 
        Toast toast = Toast.makeText(getApplicationContext(), "ERROR: Could not detect location. Please check location settings.", Toast.LENGTH_SHORT); 
        toast.show(); 
       } 
      } else { 
       Toast toast = Toast.makeText(getApplicationContext(), "Error: Not connected to google play services", Toast.LENGTH_SHORT); 
       toast.show(); 
      } 
     } 
    }); 
} 

private void getLocation() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); 
    mGoogleApiClient.connect(); 
} 
+0

どのトーストが表示されていますか? –

+0

@DanielNugentの場所を検出できませんでした。あとでもう一度試してみてください。 – Newbie

+0

フルコードを掲載できますか?特に 'mGoogleApiClient' –

答えて

1

[OK]を、ここで手順は次のとおりです。まず、依存関係を追加:

compile 'com.google.android.gms:play-services:10.2.0' 

コピー以下のコードを、あなたはそれを理解し、彼らは基本です:

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, LocationListener { 

private final String LOG_TAG = "TestApp"; 
private TextView tvLongitude, tvLatitude; 
private GoogleApiClient mGoogleApiClient; 
private LocationRequest mLocationRequest; 

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

    checkPermission(); 

    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(LocationServices.API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .build(); 

    tvLongitude = (TextView) findViewById(R.id.tvLongitude); 
    tvLatitude = (TextView) findViewById(R.id.tvLatitude); 
} 

public void checkPermission() { 
    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)) { 

      // Show an explanation 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(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        1); 

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

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case 1: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       // permission was granted, yay! Do the 
       // contacts-related task you need to do. 

      } else { 

       // permission denied, boo! Disable the 
       // functionality that depends on this permission. 

       onResume(); 
      } 
      return; 
     } 

     // other 'case' lines to check for other 
     // permissions this app might request 
    } 
} 

@Override 
protected void onStart() { 
    super.onStart(); 
    mGoogleApiClient.connect(); 
} 

@Override 
protected void onStop() { 
    mGoogleApiClient.disconnect(); 
    super.onStop(); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 

    checkPermission(); 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 

    mLocationRequest = LocationRequest.create(); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    mLocationRequest.setInterval(1000); // Update location every second 


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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. 
     checkPermission(); 
    } else { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 
} 

@Override 
public void onConnectionSuspended(int i) { 
    Log.i(LOG_TAG, "GoogleApiClient connection has been suspended"); 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
    Log.i(LOG_TAG, "GoogleApiClient connection has been failed"); 
    Log.i(LOG_TAG, "" + connectionResult); 

} 

@Override 
public void onLocationChanged(Location location) { 
    Log.i(LOG_TAG, location.toString()); 
    tvLongitude.setText(Double.toString(location.getLongitude())); 
    tvLatitude.setText(Double.toString(location.getLatitude())); 
} 
} 

はあなたが理解していない任意の部分を確認して下さい。私はかなりまっすぐに推測する。

+0

そのような場合は、代わりに 'SecurityException'ケースに入るでしょう。 –

+0

@BhaveshMisriあなたが入力したものはすべて意味がありました。ちょうど1つの質問があります。 checkPermission()の "explanation"コメントは、いくつかのコードに置き換えられることを意味していますか?それは愚かな質問かもしれないが、私は実際にはわからない – Newbie

+0

また、私は行にエラーを解決し続ける:LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient、mLocationRequest、this); – Newbie

関連する問題