在 Fused Location 的帮助下请求位置更新时应用程序崩溃
Posted
技术标签:
【中文标题】在 Fused Location 的帮助下请求位置更新时应用程序崩溃【英文标题】:App Crashes While Requesting Location Updates With The Help Of Fused Location 【发布时间】:2018-10-03 20:44:19 【问题描述】:我在
的帮助下请求位置更新LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
locationRequest, locationListener);
但是当我试图在 swtich onClickListener 上提及这一点时,它崩溃了。然而,android Studio 本身并没有抛出错误。
作为此功能的一部分,我已经添加了请求融合位置、粗略位置和 Internet 的权限。我什至在请求更新之前尝试连接 google Api 客户端 喜欢。,
if(googleApiClient.isConnected)
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
locationRequest, locationListener);
else
buildGoogleApiClient();
但我无法解决错误。 使用 Fused Location Provider Api 移除位置请求也会导致应用崩溃。
我的清单文件有如下代码。如您所见,我已经请求了所需的权限
我的 XML 文件是
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_
android:layout_
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
tools:context="com.matt.dumate.Welcome" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar3"
android:layout_
android:layout_
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#0064a2"
android:weightSum="2">
<RelativeLayout
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="start">
<com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch
android:id="@+id/locationSwitch"
android:layout_
android:layout_
android:layout_alignParentStart="true"
android:layout_centerInParent="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp"
app:ball_press_color="@android:color/white"
app:ball_release_color="@color/ballReleaseColor"
app:base_press_color="@color/basePressColor"
app:base_release_color="@color/baseReleaseColor"
app:icon_press="@drawable/ic_location_on"
app:icon_release="@drawable/ic_location_off" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
<Button
android:id="@+id/bookingButton"
android:layout_
android:layout_
android:layout_alignBottom="@+id/toolbar3"
android:layout_alignParentStart="true"
android:layout_marginBottom="5dp"
android:layout_marginStart="90dp"
android:layout_marginTop="5dp"
android:background="@drawable/bookingbutton"
android:gravity="center"
android:text="@string/booking"
android:textColor="@android:color/white" />
</RelativeLayout>
这是我的 java 文件。我也在学习创建一个像 Uber 这样的应用程序。
package com.matt.dumate;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Welcome extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
MaterialAnimatedSwitch location_switch;
SupportMapFragment mapFragment;
private Button btnBooking;
private Location lastLocation;
private GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener;
private LocationRequest locationRequest;
private LocationListener locationListener;
private LocationManager locationManager;
private Marker marker;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private final int RequestCode = 10;
private final int ResourceCode = 11;
private DatabaseReference databaseReference;
GeoFire geoFire;
@Override
protected void onCreate(Bundle savedInstanceState)
checkLocationPermission();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
/***/
databaseReference = FirebaseDatabase.getInstance().getReference("Drivers");
geoFire = new GeoFire(databaseReference);
setupLocation();
@Override
public void onMapReady(GoogleMap googleMap)
setupUiViews();
mMap = googleMap;
location_switch.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
if(location_switch.isChecked())
displayLocation();
Snackbar.make(mapFragment.getView(), "You Are Online", Snackbar.LENGTH_SHORT).show();
else
stopLocationUpdates();
Snackbar.make(mapFragment.getView(), "You Are Offline", Snackbar.LENGTH_SHORT).show();
if (marker != null)
marker.remove();
);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
switch (requestCode)
case RequestCode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
if (checkPlayServices())
buildGoogleApiClient();
createLocationRequest();
if (location_switch.isChecked())
displayLocation();
public void checkLocationPermission()
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
ActivityCompat.requestPermissions(this, new String[]Manifest.permission.ACCESS_FINE_LOCATION, RequestCode);
else
ActivityCompat.requestPermissions(this, new String[]Manifest.permission.ACCESS_FINE_LOCATION, RequestCode);
else
Toast.makeText(this, "Location Permissions Granted", Toast.LENGTH_SHORT).show();
@Override
public void onConnected(@Nullable Bundle bundle)
locationRequest = LocationRequest.create()
.setInterval(1000)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
startLocationUpdates();
displayLocation();
@Override
public void onConnectionSuspended(int i)
googleApiClient.connect();
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
@Override
public void onLocationChanged(Location location)
lastLocation = location;
displayLocation();
protected synchronized void buildGoogleApiClient()
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
private void setupUiViews()
btnBooking = findViewById(R.id.bookingButton);
location_switch = findViewById(R.id.locationSwitch);
private void displayLocation()
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
return;
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null )
if(location_switch.isChecked())
final Double lat = lastLocation.getLatitude();
final Double lng = lastLocation.getLongitude();
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener()
@Override
public void onComplete(String key, DatabaseError error)
if (marker != null)
marker.remove();
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.carmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
else
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.carmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
);
else
Toast.makeText(this, "Cannot Get Location Updates", Toast.LENGTH_SHORT).show();
else
Log.d("Error", "Cannot Get Your Location");
private void setupLocation()
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
ActivityCompat.requestPermissions(this, new String[]Manifest.permission.ACCESS_FINE_LOCATION, RequestCode);
else
ActivityCompat.requestPermissions(this, new String[]Manifest.permission.ACCESS_FINE_LOCATION, RequestCode);
else
if (checkPlayServices())
buildGoogleApiClient();
createLocationRequest();
private void createLocationRequest()
locationRequest = LocationRequest.create()
.setInterval(1500)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(0);
private boolean checkPlayServices()
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode, this, ResourceCode).show();
else
Toast.makeText(this, "This Device Is Not Supported", Toast.LENGTH_SHORT).show();
finish();
return false;
return true;
private void stopLocationUpdates()
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
return;
//LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, locationListener);
private void startLocationUpdates()
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
return;
//LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationListener);
【问题讨论】:
However there was no error thrown Android Studio itself
如果发生崩溃,有堆栈跟踪,请发布
实际上唯一的问题是在最后一个参数上我放了 locationListener 我只需要把它改成这个。 LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationListener);还是谢谢。
【参考方案1】:
您在locationListener
的帮助下请求了位置更新,但您尚未初始化。您可以通过初始化位置侦听器或在代码的给定语句中将locationListener
更改为this
来解决此问题。
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationListener);
到:
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
【讨论】:
【参考方案2】:融合定位服务的实现已经改变,你可以在没有GoogleApiClient
的情况下做到这一点。你可以这样试试,
将所需的位置库添加到
build.grade
implementation 'com.google.android.gms:play-services-location:15.0.0'
为清单添加所需的权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
在
Welcome
活动内
public class Welcome extends AppCompatActivity implements OnMapReadyCallback
...
...
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest = LocationRequest.create()
.setInterval(1000)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
private LocationCallback mLocationCallback = new LocationCallback()
@Override
public void onLocationResult(LocationResult result)
super.onLocationResult(result);
for (Location location : result.getLocations())
if (location != null)
displayLocation(result.getLastLocation());
break;
;
...
...
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
...
...
// Get fussed location instance
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
...
...
@Override
public void onMapReady(GoogleMap googleMap)
...
...
// Check if location permission is granted
if (!hasLocationPermission())
// Request location permission
else
// Get the last known location
startLocationUpdate();
private void startLocationUpdate()
try
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>()
@Override
public void onSuccess(Location location)
if (location != null)
displayLocation(location);
else
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
);
catch (SecurityException ex)
ex.printStackTrace();
private boolean hasLocationPermission()
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED;
private void stopLocationUpdate()
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
private void displayLocation(Location location)
// do something
...
...
【讨论】:
实际上唯一的问题是在最后一个参数上我放了 locationListener 我只需要把它改成这个。 LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationListener);不管怎么说,还是要谢谢你。这也奏效了。以上是关于在 Fused Location 的帮助下请求位置更新时应用程序崩溃的主要内容,如果未能解决你的问题,请参考以下文章
Android:关闭位置时,Google Fused Location 不起作用
使用 Fused Location Provider 查找位置源
如何在 Service 类中使用 Fused Location Provider?
使用 Fused Location Provider 获取启用/禁用位置服务的信息