onLocationChange()没有被调用...使用FuseLocationApi ...检查所有解决方案尝试了所有这些....但仍然没有任何工作

时间:2018-01-30 13:31:23

标签: java android api firebase dictionary

出于检查目的,我在代码中的每个方法中插入了log。 onConnected()方法被调用,但它没有进一步到OnLocationChanged()

DriverMapActivity

public class DriverMapActivity extends FragmentActivity implements OnMapReadyCallback, View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

private GoogleMap mMap;
private Button save;
GoogleApiClient mgooogleapiclient;
Location mlastlocation;
LocationRequest mlocationRequest;
Marker marker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_driver_map);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    save = (Button) findViewById(R.id.save);
    save.setOnClickListener(this);
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    // LatLng sydney = new LatLng(-34, 151);
    //  mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    //  mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

    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) {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
        Log.d("conn","api got");

    }
    else
    {
        checkLocationPermission();
        Log.d("conn","api gotout");
    }
    Log.d("conn","api gotout");



}

protected synchronized void buildGoogleApiClient() {
    mgooogleapiclient=new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mgooogleapiclient.connect();
    Log.d("buildapi","api co");
}

@Override
public void onClick(View v) {


}

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

    mlocationRequest = new LocationRequest();
    mlocationRequest.setInterval(1000);
    mlocationRequest.setFastestInterval(1000);
    mlocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    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) {

        LocationServices.FusedLocationApi.requestLocationUpdates(mgooogleapiclient, mlocationRequest, this);
    }
    Log.d("conn","in on vconnected");

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
 mlastlocation=location;
 LatLng latLng=new LatLng(location.getLatitude(),location.getLongitude());
 mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
 mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
 Log.d("see location","lati:  "+location.getLatitude()+"   longi:"+location.getLongitude());
 MarkerOptions markerOptions=new MarkerOptions();
 markerOptions.position(latLng);
 markerOptions.title("Current position");
 markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
 if(marker!=null)
 {
     marker.remove();
 }
 marker=mMap.addMarker(markerOptions);

 DatabaseReference ref=FirebaseDatabase.getInstance().getReference("DriversAvailable");
    GeoFire geoFire=new GeoFire(ref);
    geoFire.setLocation("DriverId",new GeoLocation(location.getLatitude(),location.getLongitude()));
}

@Override
protected void onStop() {
    super.onStop();
    DatabaseReference ref=FirebaseDatabase.getInstance().getReference("DriversAvailable");
    GeoFire geoFire=new GeoFire(ref);
    geoFire.removeLocation("DriverId");
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                android.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.
            new AlertDialog.Builder(this)
                    .setTitle("Location Permission Needed")
                    .setMessage("This app needs the Location permission, please accept to use location functionality")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(DriverMapActivity.this,
                                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSIONS_REQUEST_LOCATION );
                            Log.d("conn","in dialog box");
                        }
                    })
                    .create()
                    .show();


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION );
        }
    }
}
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                if (ContextCompat.checkSelfPermission(this,
                        android.Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mgooogleapiclient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                    LocationServices.FusedLocationApi.requestLocationUpdates(mgooogleapiclient, mlocationRequest, this);
                }

            } else {


                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }


    }
}
}

Android清单文件

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

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

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

构建Gradle文件

apply plugin: 'com.android.application

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.user.vypodriver"
    minSdkVersion 17
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-maps:11.0.4'
    implementation 'com.google.firebase:firebase-database:11.0.4'
    testImplementation 'junit:junit:4.12'
    implementation 'com.google.android.gms:play-services-location:11.0.4'
    compile 'com.firebase:geofire-android:2.2.0'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
apply plugin: 'com.google.gms.google-services'

**这里我试图每秒获取驱动程序位置并希望将其更新为firebase但是onLocationChange不会被调用。试图在Noghut **上运行的Android手机上运行它

2 个答案:

答案 0 :(得分:2)

可能没有调用方法requestLocationUpdates,因为您没有位置权限。

在此处添加其他内容:

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) {
    LocationServices.FusedLocationApi.requestLocationUpdates(mgooogleapiclient, mlocationRequest, this);
} else {
    checkLocationPermission(); 
}

答案 1 :(得分:0)

你有一个错误,我认为是错字。

onMapReady()中,您可以通过以下方式检查权限状态:

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)

但是,在onConnected()方法中,您的条件如下:

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)

请注意,第二个条件要求ACCESS_COARSE_LOCATION为false,第一个条件要求它为真。