When you need to do some tasks that need to load like network operations or something that may seem like your application is stuck, you should use a separate thread for this. However, this other thread can not update the graphical interface, that is, it should not change the contents of any visual component. To work around this problem, there is the AsyncTask class, which allows us to implement the code that will be executed before, during and after the execution of some task performed in the background, you can put this class inside your activity. Follow the code
import android.location.Location;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
public class testeActivity extends ActionBarActivity {
ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teste);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
}
private void exibirProgress(boolean exibir) {
mProgressBar.setVisibility(exibir ? View.VISIBLE : View.GONE);
}
class MinhaTask extends AsyncTask<Location,Void,Location> {
@Override
protected void onPreExecute() {
super.onPreExecute();
exibirProgress(true);
}
@Override
protected Location doInBackground(Location... params) {
return medotodoRetornaLocation();
}
@Override
protected void onPostExecute(Location location) {
super.onPostExecute(location);
exibirProgress(false);
metodoAtualizaAInterfaceGrafica(location);
}
}
}
The display method displayProgress (boolean); is the method responsible for displaying or not progress in the view.
View progress statement:
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleLarge"
android:layout_centerInParent="true"
android:visibility="gone"
android:id="@+id/progressBar"
/>
Now add the methods that update the graphical interface and the one that will get the location and be happy! \ o /
To learn more about the AsyncTask class, follow the link:
link