#java #android
#java #Android
Вопрос:
У меня есть некоторый код, который использует LocationManager для определения местоположения с помощью GPS. Когда я пытаюсь запустить его на своем телефоне (Alcatel OneTouch Fierce XL), я немедленно получаю уведомление «К сожалению (название моего приложения) остановлено». Эта ошибка возникает только тогда, когда службы определения местоположения включены на смартфоне, в противном случае приложение работает без сбоев.
Я пробовал любой пример кода, который мог заставить работать, и у меня тот же результат.
Вот мой код:
Инициализация GPS:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED amp;amp; ActivityCompat.checkSelfPermission(this, permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
Методы, которые я использую:
//Location stuff
public void onLocationChanged(Location location) {
Toast.makeText(this, "Latitude:" location.getLatitude() ", Longitude:" location.getLongitude(), Toast.LENGTH_LONG);
try {
wait(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
Трассировка стека:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.eas, PID: 11330
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.eas/com.example.eas.MainActivity}: java.lang.ClassCastException: com.example.eas.MainActivity cannot be cast to android.location.LocationListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2427)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:735)
Caused by: java.lang.ClassCastException: com.example.eas.MainActivity cannot be cast to android.location.LocationListener
at com.example.eas.MainActivity.onCreate(MainActivity.java:50)
at android.app.Activity.performCreate(Activity.java:6036)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2427)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:735)
Ответ №1:
Ваше исключение:
Caused by: java.lang.ClassCastException: com.example.eas.MainActivity cannot be cast to android.location.LocationListener
Похоже, что это происходит из:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
this
(что, по-видимому, является вашей активностью) не реализует LocationListener
интерфейс. Добавьте этот интерфейс и убедитесь, что вы внедрили все методы, требуемые этим интерфейсом.
Вы можете узнать больше об интерфейсах Java в документации Oracle.