[英]Get location updates after GPS enabled by user
我有一個簡單的應用程序,該應用程序當前僅詢問必要的權限,如果GPS關閉,則會出現AlertDialog詢問您是否要將其打開。 接受后,進入GPS選項,啟用它,然后返回我的App,我想更新位置,在這里我迷路了。
換句話說,我正在嘗試執行此處所述的內容: https : //stackoverflow.com/a/43396965/7060082
不幸的是,我無法完成它,這個例子讓我理解起來有些復雜。 這是我的一段代碼,顯示了相關的位:
private void checkGPS() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.GPS_error)
.setCancelable(false)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gps, 1);
getLatLon();
}
})
.setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
getLatLon();
}
}
private void getLatLon() {
//manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = manager.getBestProvider(criteria, false);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
manager.getLastKnownLocation(provider);
if (location != null) {
Toast.makeText(this, "This is my location: " + location.getLongitude() + ", " + location.getLatitude(), Toast.LENGTH_SHORT).show();
} else {
// manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
//location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
/*
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
*/
}
}
}
@Override
public void onLocationChanged(Location l) {
location = l;
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
}
在請求ACCESS_FINE_LOCATION許可(在清單上也有說明)之后,我調用checkGPS() 。 如前所述,讓我們啟用或禁用GPS。 如果啟用,我將調用getLatLon() 。 如果有一個lastKnownLocation,那么很好,如果沒有...
在這里我迷路了。 我調用requestLocationUpdates ,然后什么也不做,等待onLocationChanged接收位置更新並執行其余代碼。 我做對了嗎? 結果是我單擊按鈕,打開了GPS。 再次單擊該按鈕,沒有任何反應。
任何對此的幫助將有所幫助。 非常感謝您的寶貴時間。
我在這里開發了融合的位置api演示應用程序和實用程序包。
如果對您有用,請嘗試一下。 要使用融合的位置api獲取位置,您只需要編寫以下代碼段即可...
new LocationHandler(this)
.setLocationListener(new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// Get the best known location
}
}).start();
如果要自定義它,只需在這里找到文檔...
https://github.com/abhishek-tm/general-utilities-android/wiki/Location-Handler
我已經根據您的需要編寫了一個示例代碼,它將在內部處理GPS啟用/禁用對話框,請嘗試此操作...
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import in.teramatrix.utilities.service.LocationHandler;
import in.teramatrix.utilities.util.MapUtils;
/**
* Lets see how to use utilities module by implementing location listener.
*
* @author Khan
*/
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap map;
private Marker marker;
private LocationHandler locationHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtaining an instance of map
FragmentManager manager = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) manager.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
this.locationHandler = new LocationHandler(this)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(5000)
.setFastestInterval(10000)
.setLocationListener(this);
}
@Override
public void onMapReady(GoogleMap map) {
this.map = map;
this.locationHandler.start();
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (marker == null) {
marker = MapUtils.addMarker(map, latLng, R.drawable.ic_current_location);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 500, null);
} else {
marker.setPosition(latLng);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (locationHandler != null) {
locationHandler.stop();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LocationHandler.REQUEST_LOCATION) {
locationHandler.start();
}
}
}
希望對您有幫助。
在禁用GPS的情況下,您的當前代碼不會在調用getLatLon()
之前等待用戶做出選擇。
您將需要添加onActivityResult()
覆蓋,該覆蓋將在用戶返回您的應用時被調用。
首先,對於禁用GPS的情況,請在checkGPS()
方法中刪除對getLatLon()
的調用:
private void checkGPS() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.GPS_error)
.setCancelable(false)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gps, 1);
//Remove this:
//getLatLon();
}
})
.setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
getLatLon();
}
}
然后,添加onActivityResult()
覆蓋,再次檢查設置,如果現在已啟用,則調用getLatLon()
:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
getLatLon();
}
}
在忙於其他項目一段時間后,回到這個項目,我刪除了getLatLon();。 從checkGPS()函數; 功能,僅此而已。 我正在使用仿真器檢查它是否正常運行,但是我忘記了該仿真器的經度和緯度值是固定的,因此您沒有像真正的手機那樣獲得任何更新,因此看起來好像在正常工作。
有點像紐比的錯誤。 無論如何,謝謝您的報價。 看看做同一件事的不同方式很有趣。
薩托克斯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.