我是Android新手,我希望点击按钮获取current location
。我关注this documentation作为教程。除showLocation()
外,所有功能都正常工作。如果我只是在这个函数中写一个toast消息,那么它工作正常但是当我添加代码来获取位置时,我在app ShanTest app unfortunately stopped
中出错。
我尝试评论下面的代码,并用TOAST消息替换它,然后它工作正常。出现错误的代码如下: -
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
onLocationChanged(location);
}
else {
Toast.makeText(getApplicationContext(), "Oops", Toast.LENGTH_SHORT).show();
}
}
});
SDK Manager
的build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
dataBinding.enabled = true
defaultConfig {
applicationId "com.example.borntoflirt.design1"
minSdkVersion 21
targetSdkVersion 25
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(dir: 'libs', include: ['*.jar'])
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:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-location:11.0.4'
testCompile 'junit:junit:4.12'
}
events.java
package com.example.borntoflirt.design1;
import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.media.MediaPlayer.OnCompletionListener;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.widget.Toast;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class events extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private Button mTorchOnOffButton;
private Boolean isTorchOn;
private Boolean isFlashAvailable;
private FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
mTorchOnOffButton = (Button) findViewById(R.id.mTorchOnOffButton);
isFlashAvailable = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
isTorchOn = false;
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (isFlashAvailable) {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
}
else {
Toast.makeText(getApplicationContext(), "Flash is not supported", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void showToast(View v) {
Context context = getApplicationContext(); // OR getBaseContext()
CharSequence text = "Hello Toast";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public void showAlert(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Write your message here.");
builder.setCancelable(false);
builder.setPositiveButton(
"ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do Task
Toast.makeText(getApplicationContext(),
"You clicked on OK", Toast.LENGTH_SHORT)
.show();
}
});
builder.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void showDate(View v) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy HH:mm:ss");
String currentDateTime = simpleDateFormat.format(calendar.getTime());
Toast.makeText(getApplicationContext(), currentDateTime, Toast.LENGTH_LONG).show();
}
public void showLocation() {
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if( permissionCheck != PackageManager.PERMISSION_GRANTED ) {
//Toast.makeText(getApplicationContext(), "Granted", Toast.LENGTH_SHORT).show();
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
onLocationChanged(location);
}
else {
Toast.makeText(getApplicationContext(), "Oops", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(getApplicationContext(), "Permission Not Granted", Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged(Location location) {
// New location has now been determined
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
假设在清单中设置了所有权限,并且依赖性良好。
mFusedLocationClient似乎没有在代码中的任何位置初始化。根据{{3}}
在onCreate中执行此操作
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);