我需要每 10 秒显示一次 toast ,所以我可以使用 handler.postDelayed
线程来解决这个问题。但是这个线程卡住 UI 1-2 秒,那么我怎样才能删除卡住的 UI?
这是我的代码:
Runnable runnable = new Runnable() {
@Override
public void run() {
gps = new TrackGPS(this);
if (gps.canGetLocation()) {
longitude = gps.getLongitude();
latitude = gps.getLatitude();
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
mTextView.setText(address + "\n" + "Lat:" + latitude + "Lon:" + longitude);
}
handler.postDelayed(this, 10000);
}
};
Handler handler = new Handler();
handler.postDelayed(runnable, 10000);
最佳答案
这是一个 Activity
类,它显示了您应该在何处声明和初始化某些字段,以及如何使用 AsyncTask
在后台线程中运行地理编码器。代码未按原样编译,因为原始代码 fragment 缺少某些类型和声明。
public class MainActivity extends Activity {
private Handler mHandler;
private Runnable mRunnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize other stuff
mHandler = new Handler(Looper.getMainLooper());
mRunnable = new Runnable() {
@Override
public void run() {
new LocationAsyncTask().execute();
}
};
mHandler.postDelayed(mRunnable, 10000);
}
private class LocationAsyncTask extends AsyncTask<Void, Void, String[]> {
@Override
protected String[] doInBackground(Void... params) {
gps = new TrackGPS(this);
if (gps1.canGetLocation()) {
longitude = gps.getLongitude();
latitude = gps.getLatitude();
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String[] strings = new String[3];
strings[0] = address;
strings[1] = latitude;
strings[2] = longitude;
return strings;
} else {
return null;
}
}
@Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
if (strings != null) {
updateText(strings[0], strings[1], strings[2]);
}
mHandler.postDelayed(mRunnable, 10000);
}
}
}
关于android - 如何在 Android 中执行 handler.postDelayed 时删除卡住 UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42972802/