2

如您所知,Android 开发指南中有一个很好的可下载示例,名为“Location Aware”

我对用这段代码编写的处理程序有疑问。在同一个类中将 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;
        }
    }

    ...............
4

2 回答 2

2

是的。我们可以使用它。这没有错。如果你愿意,你也可以将它们分成两个类。

于 2013-02-23T06:55:52.890 回答
1

不,您在 java 中使用匿名内部类,它获取对外部对象实例的引用。(在这种情况下你的处理程序)

将内部类设为静态,并将 PARENT_CLASS 作为构造函数参数传入,并使用 Wea​​kReference 来存储引用。

这可以防止垃圾收集器中的循环依赖链。

https://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html

WeakReference 仍然允许您轻松地“指向”一个对象,但是当该对象没有其他(强)引用时......它将被垃圾收集。(这是期望的结果)(在 RAM 有限的 Android 中尤为重要)

编辑:这是一个非常微妙的内存泄漏,除非您专门寻找它,否则很难捕捉到它。其原因是 Java 添加了对所有非静态内部类的隐式引用(我不是 100% 确定 lambda 表示法,但我认为不是……但我需要研究一下……)到创建内部类实例的实例对象...这会导致 GC 跟踪引用的循环...并在不需要时将两个对象保存在内存中的内存泄漏。(请注意,当您处理自己的线程时,这一点更为重要......但仍然是一个很好的实践)

于 2016-05-22T13:02:21.767 回答