#android #android-layout #android-location
#Android #android-макет #android-location
Вопрос:
Я разрабатываю простое приложение «Регистрация» и сталкиваюсь с некоторыми проблемами.
Когда я нажимаю кнопку ImageButton, чтобы получить местоположение, мой Logcat начинает отвечать:
GC_EXPLICIT freed 365K, 18% free 14183K/17256K, paused 2ms 4ms, total 24ms
to [...]
GC_EXPLICIT freed 137K, 1% free 17871K/18044K, paused 2ms 16ms, total 63ms
и приложение зависает.
Я уменьшил задержку, изменив RelativeLayout на LinearLayout, но проблема сохраняется.
* PS: Работает на Moto G (Motorola XT1033)
Код:
//MyLocationListener
public class MyLocationListener implements LocationListener{
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5000; // in Milliseconds
private LocationManager locationManager;
public MyLocationListener(LocationManager locationManager) {
this.locationManager = locationManager;
}
public void onLocationChanged(Location location) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener(locationManager)
);
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
public void onStatusChanged(String s, int i, Bundle b) {
}
}
// Проверка активности
public class CheckInActivity extends ActionBarActivity{
private SharedPreferences sharedPref;
private LocationManager locationManager;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkin);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
sharedPref = this.getSharedPreferences("user", Context.MODE_PRIVATE);
String truck = sharedPref.getString("name", "");
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new MyLocationListener(locationManager));
} else if (locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new MyLocationListener(locationManager));
} else {
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, new MyLocationListener(locationManager));
}
EditText folk = (EditText)findViewById(R.id.folkName);
folk.setText(truck);
}
public void setLocation(View view) {
final ProgressDialog progressDialog = new ProgressDialog(CheckInActivity.this);
final EditText addressInput = (EditText)findViewById(R.id.addressInput);
progressDialog.setMessage("Obtendo endereço atual…");
progressDialog.show();
new AsyncTask<Void, Void, Location>(){
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected Location doInBackground(Void... voids) {
android.location.Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ( location == null )
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if ( location == null )
location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
System.out.println(location);
if(location != null){
double x = location.getLatitude();
double y = location.getLongitude();
final Location finalLocation = location;
runOnUiThread(new Runnable() {
@Override
public void run() {
double x = finalLocation.getLatitude();
double y = finalLocation.getLongitude();
String x_val = String.valueOf(x);
TextView lat = (TextView)findViewById(R.id.lat);
lat.setText(x_val);
String y_val = String.valueOf(y);
TextView lon = (TextView)findViewById(R.id.lon);
lon.setText(y_val);
}
});
System.out.println(x);
System.out.println(y);
try{
Geocoder geocoder = new Geocoder(CheckInActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(x, y, 1);
final StringBuilder str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String cidade = returnAddress.getAdminArea();
String endereco = returnAddress.getAddressLine(0);
str.append(endereco).append(" - ").append(cidade);
progressDialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
addressInput.setText(str);
}
});
}else{
Toast.makeText(CheckInActivity.this,
"geocoder not present", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return location;
}
}.execute();
}
}
Ответ №1:
Я думаю, что проблема здесь:
public void onLocationChanged(Location location) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener(locationManager)
);
}
Каждый раз, когда вы получаете обновление местоположения, вы регистрируете нового прослушивателя местоположения, поэтому в следующий раз вы получите два обновления местоположения и зарегистрируете еще два прослушивателя местоположения, затем четыре, затем 8, после чего система останавливается.
Комментарии:
1. Используя ваш ответ в качестве основы, я просто ввел некоторое значение: private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; теперь с 50 метрами слушатель не умирает при циклировании.