2016-04-03 8 views
0

私は、ユーザーの現在地を読み取る簡単なAndroid GPSアプリケーションを作成しようとしています。Android GPSアプリケーション(ユーザーの所在地を取得する) - アクセスできないアクセス

これを行うには、私は許可を要求する必要があります。私は、Google独自のAndroidページでチュートリアルに従ってきました。

私のアプリはうまく起動し、アクセス権の要求を開始する必要があるところまで達しても、それ以上は動作しません。

私はテキストをtextViewsに印刷するアプリにいくつかの "デバッグメッセージ"を入れました。 onConnected()メソッドでは「1」にしかなりません。

私は間違って何をしているのか?事前に多くの感謝!ここで

は、私の活動のJavaコード

public class StartActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener { 

    private Location mLastLocation; 
    private boolean locationPermissionGoodToGo = false; 

    private final int MY_PERMISSION_ACCESS_FINE_LOCATION = 1; 

    // Google client to interact with Google API 
    private GoogleApiClient mGoogleApiClient; 

    // UI elements 
    private TextView mLatitudeText,mLongitudeText, mTextTest, mTextPerRes; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_start); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     // Create an instance of GoogleAPIClient. 
     if (mGoogleApiClient == null) { 
      mGoogleApiClient = new GoogleApiClient.Builder(this) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .addApi(LocationServices.API) 
        .build(); 
     } 
     mLatitudeText = (TextView) findViewById(R.id.mLatitudeText); 
     mLongitudeText = (TextView) findViewById(R.id.mLongitudeText); 
     mTextTest = (TextView) findViewById(R.id.textTest); 
     mTextPerRes = (TextView) findViewById(R.id.textPerRes); 

     LocationRequest mLocationRequest = createLocationRequest(); 

     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(mLocationRequest); 

     PendingResult<LocationSettingsResult> result = 
       LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, //mGoogleClient 
         builder.build()); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).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.menu_start, 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(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

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

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

    public boolean refreshLocation(){ 
     return false; 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     mTextPerRes.setText("Permission getting ready");//DEBUG!!! 
     mTextTest.setText("1");//DEBUG!!! 
     if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      mTextTest.setText("1.5");//DEBUG!!! 
      ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_ACCESS_FINE_LOCATION); 
     } 
     if(locationPermissionGoodToGo == true) { 
      //TODO: Kommer inte in här. Något fel med permissions! :(
      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
      mTextTest.setText("2");//DEBUG!!! 
      if (mLastLocation != null) { 
       mTextTest.setText("3");//DEBUG!!! 
       mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude())); 
       mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude())); 
      } 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    protected LocationRequest createLocationRequest() { 
     LocationRequest mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(10000); 
     mLocationRequest.setFastestInterval(5000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     return mLocationRequest; 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     mTextPerRes.setText("Permission wanted");//DEBUG!!! 
     switch (requestCode) { 
      case MY_PERMISSION_ACCESS_FINE_LOCATION: { 
       mTextPerRes.setText("Permission case right");//DEBUG!!! 
       // 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. 
        mTextPerRes.setText("Permission granted");//DEBUG!!! 
        locationPermissionGoodToGo = true; 
       } else { 
        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
       } 
       return; 
      } 
      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 
} 

そして、ここでは私のマニフェストです:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="se.adrianhansson.gpsapp" 
    android:versionCode="1" 
    android:versionName="1.0"> 

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

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="21" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 

     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 

     <activity 
      android:name=".StartActivity" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme.NoActionBar"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

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

</manifest> 

私の編集したコードを、まだ動作しません。同じ結果。

public class StartActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener { 

    private Location mLastLocation; 
    private boolean locationPermissionGoodToGo = false; 

    private final int MY_PERMISSION_ACCESS_FINE_LOCATION = 1; 

    // Google client to interact with Google API 
    private GoogleApiClient mGoogleApiClient; 

    // UI elements 
    private TextView mLatitudeText,mLongitudeText, mTextTest, mTextPerRes; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_start); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     // Create an instance of GoogleAPIClient. 
     if (mGoogleApiClient == null) { 
      mGoogleApiClient = new GoogleApiClient.Builder(this) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .addApi(LocationServices.API) 
        .build(); 
     } 
     mLatitudeText = (TextView) findViewById(R.id.mLatitudeText); 
     mLongitudeText = (TextView) findViewById(R.id.mLongitudeText); 
     mTextTest = (TextView) findViewById(R.id.textTest); 
     mTextPerRes = (TextView) findViewById(R.id.textPerRes); 

     LocationRequest mLocationRequest = createLocationRequest(); 

     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(mLocationRequest); 

     PendingResult<LocationSettingsResult> result = 
       LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, //mGoogleClient 
         builder.build()); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).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.menu_start, 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(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

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

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

    public boolean refreshLocation(){ 
     return false; 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     mTextPerRes.setText("Permission getting ready");//DEBUG!!! 
     mTextTest.setText("1");//DEBUG!!! 
     if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      mTextTest.setText("1.5");//DEBUG!!! 
      ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_ACCESS_FINE_LOCATION); 
     } 
     setCoordinates(); 
//  original location of setCoordinates() code 
    } 

    public void setCoordinates(){ 
     if(locationPermissionGoodToGo == true) { 
      //TODO: Kommer inte in här. Något fel med permissions! :(
      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
      mTextTest.setText("2");//DEBUG!!! 
      if (mLastLocation != null) { 
       mTextTest.setText("3");//DEBUG!!! 
       mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude())); 
       mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude())); 
      } 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    protected LocationRequest createLocationRequest() { 
     LocationRequest mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(10000); 
     mLocationRequest.setFastestInterval(5000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     return mLocationRequest; 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     mTextPerRes.setText("Permission wanted");//DEBUG!!! 
     switch (requestCode) { 
      case MY_PERMISSION_ACCESS_FINE_LOCATION: { 
       mTextPerRes.setText("Permission case right");//DEBUG!!! 
       // 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. 
        mTextPerRes.setText("Permission granted");//DEBUG!!! 
        locationPermissionGoodToGo = true; 
        setCoordinates(); 
       } else { 
        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
        locationPermissionGoodToGo = false; 
       } 
       return; 
      } 
      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 
} 

答えて

1

requestPermissions()は非同期です。呼び出した直後にlocationPermissionGoodToGoをチェックしています。これはです。多くはです。

if(locationPermissionGoodToGo == true)ブロックのコードを別の方法に移動します。 checkSelfPermission()に許可があると表示された場合は、すぐに別の方法を呼び出してください。それ以外の場合は、onRequestPermissionResult()に電話してください。locationPermissionGoodToGoからtrueに設定します。

+0

返信いただきありがとうございます。私はこれをやろうとしましたが、結果は同じで、うまくいかないようです。今あなたが私に言ったことを誤解しているかもしれません。上記の私のメインポストの最後に、新しい、編集済みのJavaコードを追加しました。 –

+0

@AdrianHansson:「** checkSelfPermission()がアクセス権を持っていると言っている場合**、すぐに別のメソッドを呼び出してください。すでに許可を得ているだけでなく、常にそれを呼び出すことになります。その 'setCoordinates()'呼び出しをラップするために 'else'ブロックを使います。そのため、あなたは既にパーミッションを持っているので(' requestPermissions() 'を呼び出す必要はありません)のみ実行されます。 – CommonsWare

+0

@AdrianHansson:[このサンプルアプリケーション](https://github.com/commonsguy/cw-omnibus/tree/master/Location/FusedNew)は、Play Servicesの融合ロケーションプロバイダを操作するコンテキストで実行時アクセス許可をリクエストする方法を示しています。 – CommonsWare

関連する問題