gpt4 book ai didi

android - 在同一个类中将 Handler 与 Async Task 一起使用是否正确?

转载 作者:搜寻专家 更新时间:2023-11-01 09:01:46 27 4
gpt4 key购买 nike

如您所知,有 a good downloadable sample called "Location Aware" in the Android Development Guide .

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

...............

最佳答案

是的。我们可以使用它。这没有错。如果需要,您也可以将它们分成两类。

关于android - 在同一个类中将 Handler 与 Async Task 一起使用是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14547476/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com