如您所知,有a good downloadable sample called "Location Aware" in the Android Development Guide。
我对此代码中编写的Handler有疑问。在同一个类中使用Handler和Async Task是否正确?此代码是否根据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;
}
}
...............
答案 0 :(得分:2)
是。我们可以用它。这没有错。如果你愿意,你也可以将它们分成两类。
答案 1 :(得分:1)
不,您在java中使用匿名内部类,它获取对外部对象实例的引用。 (在这种情况下你的处理程序)
使内部类静态并将PARENT_CLASS作为构造函数参数传递,并使用WeakReference存储引用。
这可以防止垃圾收集器中的循环依赖链。
https://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html
WeakReference仍然允许您轻松地“指向”一个对象,但是当该对象没有其他(强)引用时......它将被垃圾收集。 (这是期望的结果)(在具有有限RAM的Android中尤为重要)
编辑:这是一个非常微妙的内存泄漏,除非你专门寻找它,否则很难捕获。原因是Java添加了对所有非静态内部类的隐式引用(我不是100%确定lambda符号,但我认为不是......但我需要研究那......)创建内部类实例的实例对象...这导致GC跟踪引用的循环...并且在不需要时将两个对象的内存泄漏保存在内存中。 (请注意,当您处理自己的线程时,这一点更为重要......但仍然是一个很好的做法)