我有以下简单代码来获取最后一个位置:
依赖项的build.gardle 文件:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.example.naresh2575.location"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services:10.0.0'
}
在清单文件中,我使用以下权限
<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"/>
这是我的活动档案:
public class MainActivity
extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
{
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
TextView tvLatLong;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLatLong = (TextView) findViewById(R.id.tvLatLong);
buildGoogleApiClient();
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
protected synchronized void buildGoogleApiClient()
{
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void onConnected(Bundle connectionHint)
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
tvLatLong.setText("Latitude: " + String.valueOf(mLastLocation.getLatitude()) + " Longitude: " + String.valueOf(mLastLocation.getLongitude()));
}
else
{
tvLatLong.setText("mLastLocation is null");
}
}
@Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "Connection suspended...", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(this, "Failed to connect...", Toast.LENGTH_SHORT).show();
}
}
上面的代码非常简单,但是当我运行我的应用程序时,我总是收到 onConnectionFailed 中写的“无法连接...”的消息。这意味着我无法连接到谷歌播放服务。我需要在哪里寻找它?
答案 0 :(得分:0)
您是否尝试使用SHA-1密钥在Google开发者控制台中创建项目?创建项目后,您可以从控制台处理身份验证密钥,您可以使用此身份验证密钥解决此问题。