我有一个使用 onLocationChanged 方法的 Activity ,并在执行解析查询时进行 toast 。效果很好。但是,当我转到另一个 Activity (它是 map Activity )时,如果我更改坐标(我正在使用模拟器),则会弹出 toast。我想知道为什么 onLocationChanged 方法仍在运行。我认为这可能是由于上下文所致,但我在上下文字段中指定了 Activity 。
locationManager = (LocationManager) DriverChoicesActivity.this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
final ParseGeoPoint parseGeoPoint = new ParseGeoPoint(location.getLatitude(), location.getLongitude());
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null && objects.size() > 0) {
for (ParseObject object : objects) {
object.put("driverLocation", parseGeoPoint);
object.saveInBackground();
Toast.makeText(DriverChoicesActivity.this, "User found", Toast.LENGTH_SHORT).show();
}
}
}
});
updateRequestList(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
所有内容均位于原始 Activity (DriverChoicesActivity.class) 的 onCreate 内。另一个 Activity (DriverMapActivity.class) 除了从该 Activity 获取 Intent 以收集一些纬度和经度点之外,没有任何代码。这是实现 Intent 的代码(也在 onCreate 中)
requestListView.setAdapter(arrayAdapter);
requestListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (requestLatitude.size() > position && requestLongitude.size() > position) {
if (Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(DriverChoicesActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location getLastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (getLastKnownLocation != null) {
Intent intent = new Intent(getApplicationContext(), DriverMapActivity.class);
intent.putExtra("requestLatitude", requestLatitude.get(position));
intent.putExtra("requestLongitude", requestLongitude.get(position));
intent.putExtra("driverLatitude", getLastKnownLocation.getLatitude());
intent.putExtra("driverLongitude", getLastKnownLocation.getLongitude());
startActivity(intent);
}
}
}
}
});
我认为我的问题与上下文有关。如果有人可以解释一下。
谢谢
最佳答案
您必须添加:
locationManager.removeUpdates(监听器)
;
在进行下一个 Activity 之前。
和
LocationManager locationManager;
LocationListener locationListener;
在顶部,类声明下
关于java - onLocationChanged 方法仍在不同的 Activity 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46105864/