我正在尝试获取用户的当前位置。但为了做到这一点,我需要在我的代码中启用Google Play服务。因此,在我能够执行更多代码(例如查找用户的当前位置)之前,我先在代码中检查checkPlayService()
方法。我的代码主要遵循this教程。
问题在于每次我的代码都会返回Device is not supported.
吐司,这可能意味着我没有在我的Android工作室中正确设置Google Play服务,或者我的代码可能有问题?我知道这方面已经有很多问题,但似乎没有任何答案可以解决这个问题,至少对于我看到的问题。请帮忙,我已经尝试了所有的事情。
我在AndroidManifest中有这些行:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="replaced_my_actual_key_with_this_statement" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
我的依赖关系:
compile 'com.google.android.gms:play-services-places:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'
compile 'com.google.android.gms:play-services:11.0.4'
代码:
public class FindLocation extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks {
private GoogleApiClient mGoogleApiClient;
private TextView selectLocation;
private static final int PERMISSION_REQUEST_TO_ACCESS_LOCATION = 1;
private LocationManager lm;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Location mLastLocation;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_location);
lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
selectLocation = (TextView) findViewById(R.id.selectLocation);
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
}
getCurrentLocation();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
private void getCurrentLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.i("THIS", "Permission NOT Granted!");
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_REQUEST_TO_ACCESS_LOCATION);
return;
}
Log.i("THIS", "Permission GRANTED!");
isLocationEnabled();
displayLocation();
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_TO_ACCESS_LOCATION: {
Log.i("THIS", "Permission Deciding...");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
Log.i("THIS", "Permission DENIED!");
// Permission denied, boo!
// Disable the functionality that depends on this permission.
}
return;
}
// Add further 'case' lines to check for other permissions this app might request.
}
}
public void isLocationEnabled() {
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Location Service not enabled!");
dialog.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
private boolean checkPlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result, PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return true;
}
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); // ALLOWED
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
selectLocation.setText(latitude + ", " + longitude);
} else {
selectLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.e("THIS", "GoogleApiClient connection failed: " + connectionResult.getErrorMessage());
}
}
答案 0 :(得分:1)
尝试this回答。
什么时候想要你的位置。使用以下代码检索位置并将其显示在textview
mLocationResolver.resolveLocation(this, new LocationResolver.OnLocationResolved() {
@Override
public void onLocationResolved(Location location) {
// Do what ever you want
textview.setText("latitude : " +location.getLatitude() + ", Longitude : "+ location.getLongitude() + "");
}
});
答案 1 :(得分:0)
我找到了解决方案。这实际上只是一个愚蠢的错误。
我复制了我所指的教程中的代码,却没有意识到checkPlayServices()
方法下的if else语句中存在轻微的错误(至少对我的应用程序而言)。更正后的代码如下所示。
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
Log.i("THISS", "HII_1");
} else {
Toast.makeText(this, "Device Not Supported", Toast.LENGTH_SHORT).show();
//Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}