Reputation: 1892
I need to show a toast after every 10 seconds, so I can use handler.postDelayed
thread to solve this. But this thread freeze UI for 1-2 seconds, so how can I remove the freeze UI?
This is my code:
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);
Upvotes: 2
Views: 1943
Reputation: 3852
Here's an Activity
class that shows where you should declare and initialize some fields, as well as how to run geocoder in a background thread with AsyncTask
. The code doesn't compile as is because the original code snippet is missing some types and declarations.
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);
}
}
}
Upvotes: 1