Урок 138. Определение местоположения. GPS координаты.
-
- Сообщения: 4
- Зарегистрирован: 09 авг 2017, 12:31
Урок 138 Определение местоположения GPS координаты
Подскажите сегодня увидел на схеме что можно поменять диск с картами для GPS .Может кто есть знает в Минске можно установить карту РБ?
Re: Урок 138. Определение местоположения. GPS координаты.
Добрый день. при выполнении задания с урока возникла проблема. Когда реализуем интерфейс(LocationListener) возникает ошибка
(
Class 'Anonymous class derived from LocationListener' must either be declared abstract or implement abstract method 'onProviderEnabled(String)' in 'LocationListener'
)
как исправить?
спасибо за помощь )
(
Class 'Anonymous class derived from LocationListener' must either be declared abstract or implement abstract method 'onProviderEnabled(String)' in 'LocationListener'
)
как исправить?
спасибо за помощь )
Re: Урок 138. Определение местоположения. GPS координаты.
Добрый день. Прошу помощи.
Урок 138 не рабочий код, проблему описал один пользователь в комментарии на ютубе, но полного решения не дали. У меня таже самая проблема, может кто-то сможет подсказать где исправить код, чтобы все заработало? На телефоне приложение просто не запускается.
Доброго времени суток! Просмотрел этот урок, всё сделал как надо, но программа AndroidStudio подчёркивает красным:
- в методе onResume():
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 10, 10, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000 * 10, 10,
locationListener);
- в методе onPause():
locationManager.removeUpdates(locationListener);
- в методе onProviderEnabled(String provider):
locationManager.getLastKnownLocation(provider).
Пробовал нажимать на красную лампочку, чтобы сгенерировать соответствующий код, красное подчёркивание исчезало, но программа всё равно не работает, при запуске выходит сообщение: "unfortunatly, ... has stopped".
Урок 138 не рабочий код, проблему описал один пользователь в комментарии на ютубе, но полного решения не дали. У меня таже самая проблема, может кто-то сможет подсказать где исправить код, чтобы все заработало? На телефоне приложение просто не запускается.
Доброго времени суток! Просмотрел этот урок, всё сделал как надо, но программа AndroidStudio подчёркивает красным:
- в методе onResume():
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 10, 10, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000 * 10, 10,
locationListener);
- в методе onPause():
locationManager.removeUpdates(locationListener);
- в методе onProviderEnabled(String provider):
locationManager.getLastKnownLocation(provider).
Пробовал нажимать на красную лампочку, чтобы сгенерировать соответствующий код, красное подчёркивание исчезало, но программа всё равно не работает, при запуске выходит сообщение: "unfortunatly, ... has stopped".
Re: Урок 138. Определение местоположения. GPS координаты.
Итак ребята, просидел несколько суток и нашел решение данной проблемы. Главное не забудьте в телефоне найти Ваше приложение и задать ему разрешение на определение местоположения в моем телефоне ксиеми это тут : Настройки - Все приложения - (выбираете из списка Ваше приложение и даете ему разрешение)
Это приложение точно запускается у меня на 7-й версии андроида и работает, определяет координаты по gps, по сети пока не работает не разобрался.
Далее код нужно поменять так:
---------------------------------------------------------------------------
1) файл MainActivity.java
2) файл AndroidManifest.xml
3) Файл activity_main.xml
4) Файл strings.xml
Это приложение точно запускается у меня на 7-й версии андроида и работает, определяет координаты по gps, по сети пока не работает не разобрался.
Далее код нужно поменять так:
---------------------------------------------------------------------------
1) файл MainActivity.java
Код: Выделить всё
package com.example.a1.mygps3;
import java.util.Date;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tvEnabledGPS;
TextView tvStatusGPS;
TextView tvLocationGPS;
TextView tvEnabledNet;
TextView tvStatusNet;
TextView tvLocationNet;
private LocationManager locationManager;
StringBuilder sbGPS = new StringBuilder();
StringBuilder sbNet = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvEnabledGPS = (TextView) findViewById(R.id.tvEnabledGPS);
tvStatusGPS = (TextView) findViewById(R.id.tvStatusGPS);
tvLocationGPS = (TextView) findViewById(R.id.tvLocationGPS);
tvEnabledNet = (TextView) findViewById(R.id.tvEnabledNet);
tvStatusNet = (TextView) findViewById(R.id.tvStatusNet);
tvLocationNet = (TextView) findViewById(R.id.tvLocationNet);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast toast = Toast.makeText(this, "Permission failed", Toast.LENGTH_SHORT);
toast.show();
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 10, 10, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000 * 10, 10,
locationListener);
checkEnabled();
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
showLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
checkEnabled();
}
@Override
public void onProviderEnabled(String provider) {
checkEnabled();
showLocation(locationManager.getLastKnownLocation(provider));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (provider.equals(LocationManager.GPS_PROVIDER)) {
tvStatusGPS.setText("Status: " + String.valueOf(status));
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
tvStatusNet.setText("Status: " + String.valueOf(status));
}
}
};
private void showLocation(Location location) {
if (location == null)
return;
if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
tvLocationGPS.setText(formatLocation(location));
} else if (location.getProvider().equals(
LocationManager.NETWORK_PROVIDER)) {
tvLocationNet.setText(formatLocation(location));
}
}
private String formatLocation(Location location) {
if (location == null)
return "";
return String.format(
"Coordinates: lat = %1$.4f, lon = %2$.4f, time = %3$tF %3$tT",
location.getLatitude(), location.getLongitude(), new Date(
location.getTime()));
}
private void checkEnabled() {
tvEnabledGPS.setText("Enabled: "
+ locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER));
tvEnabledNet.setText("Enabled: "
+ locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
}
public void onClickLocationSettings(View view) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
};
}
2) файл AndroidManifest.xml
Код: Выделить всё
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a1.mygps3">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3) Файл activity_main.xml
Код: Выделить всё
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="@+id/tvTitleGPS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/provider_gps"
android:textSize="30sp">
</TextView>
<TextView
android:id="@+id/tvEnabledGPS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvStatusGPS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvLocationGPS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvTitleNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/provider_network"
android:textSize="30sp">
</TextView>
<TextView
android:id="@+id/tvEnabledNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvStatusNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvLocationNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<Button
android:id="@+id/btnLocationSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="onClickLocationSettings"
android:text="@string/location_settings">
</Button>
</LinearLayout>
4) Файл strings.xml
Код: Выделить всё
<resources>
<string name="app_name">mygps3</string>
<string name="provider_gps">GPS</string>
<string name="provider_network">Network</string>
<string name="location_settings">Location settings</string>
</resources>
Re: Урок 138. Определение местоположения. GPS координаты.
Как заставить работать GPS в service ? После выхода из приложения service работает, но координаты прекращают поступать
Re: Урок 138. Определение местоположения. GPS координаты.
При включённом WiFi или 4G - NETWORK показывает false, подскажите в чём причина !
Re: Урок 138. Определение местоположения. GPS координаты.
В genymotion это не тестируется? Или как его настроить? Только на реальном устройстве?
У меня выдает permission failed? как это исправить. Эмулятор выдает координаты в gps, но само приложение нет. вообще пусто
У меня выдает permission failed? как это исправить. Эмулятор выдает координаты в gps, но само приложение нет. вообще пусто
Re: Урок 138. Определение местоположения. GPS координаты.
Однако забыли про этот форум. Разрешение на получение координат должен дать пользователь, где то тут надо копатьwaat2 писал(а): ↑09 авг 2021, 17:41audiobookkeeper.rucottagenet.rueyesvision.rueyesvisions.comfactoringfee.ru[url=htt.......................
Re: Урок 138. Определение местоположения. GPS координаты.
Для того чтобы приложение заработало необходимо разрешение от пользователя. Для этого я создал метод и вызываю его в onCreate перед всеми.
Реализация самого метода:
Также в слушателе LocationListener() в методе public void onProviderEnabled(String provider) пишу такой код:
В манифесте указываю оба разрешения:
Проверено на устройстве!
Код: Выделить всё
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvEnabledGPS = (TextView) findViewById(R.id.tvEnabledGPS);
tvStatusGPS = (TextView) findViewById(R.id.tvStatusGPS);
tvLocationGPS = (TextView) findViewById(R.id.tvLocationGPS);
tvEnabledNet = (TextView) findViewById(R.id.tvEnabledNet);
tvStatusNet = (TextView) findViewById(R.id.tvStatusNet);
tvLocationNet = (TextView) findViewById(R.id.tvLocationNet);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
permissionGranted();
}
Код: Выделить всё
public void permissionGranted() {
// This will be used in handling callback
int MY_PERMISSIONS = 1;
// When permission is not granted by user, show them message why this permission is needed.
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(this, "Please grant permissions to record audio", Toast.LENGTH_LONG).show();
// Give user option to still opt-in the permissions
} // Show user dialog to grant permission to record audio
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS);
// If permission is granted, then go ahead recording audio
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);// Go ahead with recording audio now
}
Код: Выделить всё
@Override
public void onProviderEnabled(String provider) {
checkEnabled();
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.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;
}
showLocation(locationManager.getLastKnownLocation(provider));
}
Код: Выделить всё
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />