如您所知,这里有a good downloadable sample called "Location Aware" in the Android Development Guide。
我有一个关于用这段代码编写的处理程序的问题。在同一个类中将处理程序与异步任务一起使用是否正确?这段代码是按照Android标准正确编写的吗?(顺便说一句,如果修复了一些错误,这个项目工作得很好。)
异步任务的参考:http://developer.android.com/reference/android/os/AsyncTask.html
public class LocationActivity extends FragmentActivity {
.....
private Handler mHandler;
private boolean mGeocoderAvailable;
...
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (savedInstanceState != null) {
mUseFine = savedInstanceState.getBoolean(KEY_FINE);
mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
} else {
mUseFine = false;
mUseBoth = false;
}
mLatLng = (TextView) findViewById(R.id.latlng);
mAddress = (TextView) findViewById(R.id.address);
..............
// Handler for updating text fields on the UI like the lat/long and address.
mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_ADDRESS:
mAddress.setText((String) msg.obj);
break;
case UPDATE_LATLNG:
mLatLng.setText((String) msg.obj);
break;
}
}
};
// Get a reference to the LocationManager object.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
...............
@Override
protected void onStart() {
super.onStart();
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
........
private void setup() {
Location gpsLocation = null;
Location networkLocation = null;
mLocationManager.removeUpdates(listener);
mLatLng.setText(R.string.unknown);
mAddress.setText(R.string.unknown);
if (mUseFine) {
mFineProviderButton.setBackgroundResource(R.drawable.button_active);
mBothProviderButton.setBackgroundResource(R.drawable.button_inactive);
gpsLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, R.string.not_support_gps);
if (gpsLocation != null) updateUILocation(gpsLocation);
} else if (mUseBoth) {
mFineProviderButton.setBackgroundResource(R.drawable.button_inactive);
mBothProviderButton.setBackgroundResource(R.drawable.button_active);
gpsLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, R.string.not_support_gps);
networkLocation = requestUpdatesFromProvider(
LocationManager.NETWORK_PROVIDER, R.string.not_support_network);
........
private void doReverseGeocoding(Location location) {
// Since the geocoding API is synchronous and may take a while. You don't want to lock
// up the UI thread. Invoking reverse geocoding in an AsyncTask.
(new ReverseGeocodingTask(this)).execute(new Location[] {location});
}
private void updateUILocation(Location location) {
// We're sending the update to a handler which then updates the UI with the new
// location.
Message.obtain(mHandler,
UPDATE_LATLNG,
location.getLatitude() + ", " + location.getLongitude()).sendToTarget();
// Bypass reverse-geocoding only if the Geocoder service is available on the device.
if (mGeocoderAvailable) doReverseGeocoding(location);
}
private final LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// A new location update is received. Do something useful with it. Update the UI with
// the location update.
updateUILocation(location);
}
.........
// AsyncTask encapsulating the reverse-geocoding API. Since the geocoder API is blocked,
// we do not want to invoke it from the UI thread.
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
@Override
protected Void doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Location loc = params[0];
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
// Update address field with the exception.
Message.obtain(mHandler, UPDATE_ADDRESS, e.toString()).sendToTarget();
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
// Update address field on UI.
Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
}
return null;
}
}
...............发布于 2013-02-23 14:55:53
是。我们可以用它。这并没有错。如果你愿意,你也可以把它们分成两个类。
发布于 2016-05-22 21:02:22
不,你在java中使用了一个匿名的内部类,它获得了对外部对象实例的引用。(在本例中为您的处理程序)
将内部类设为静态类,并将PARENT_CLASS作为构造函数参数传入,并使用WeakReference存储引用。
这可以防止垃圾收集器中出现循环依赖链。
https://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html
WeakReference仍然允许您轻松地“指向”一个对象,但是当该对象没有其他(强)引用时……它将被垃圾回收。(这是预期的结果)(在内存有限的Android中尤其重要)
编辑:这是一个非常微妙的内存泄漏,除非您专门寻找它,否则很难捕捉到它。原因是Java添加了对所有非静态内部类的隐式引用(我对lambda符号不是100%确定,但我认为不是……但我需要调查一下...)它指向创建内部类实例的instance对象...这会导致GC跟踪引用的循环...并造成两个对象在不需要时都保留在内存中的内存泄漏。(请注意,当您处理自己的线程时,这一点更重要...但这仍然是一个很好的实践)
https://stackoverflow.com/questions/14547476
复制相似问题