Is there a (thread safe) method I can call from Java on Android which will give me a handle to the foreground activity from a background task? I would like to be able to do so in order to safely post toasts on top of the top window.
Thanks.
Is there a (thread safe) method I can call from Java on Android which will give me a handle to the foreground activity from a background task? I would like to be able to do so in order to safely post toasts on top of the top window.
Thanks.
You wouldn't necessarily have to get a handle to the foreground UI activity to show a toast message. You can do this from a background thread like this:
runOnUiThread(new Runnable() {
public void run() {
// make toast, show toast
}
});
Create your own class that extends AsyncTask and pass the Activity as one of the parameters:
public class MyAsyncTask extends AsyncTask<String, String, String>{
Activity mActivity;
public MyAsyncTask (Activity mActivity){
this.mActivity = mActivity;
}
@Override
protected String doInBackground(String... urls) {
return null;
}
@Override
protected void onPostExecute(String result) {
}
}
Doing that should allow you to access the Activity (assuming it's still the foreground throughout; which may not necessarily be the case).
If there's a chance that it's not the foreground Activity, you may want to just use the:
runOnUiThread(new Runnable() {
public void run() {
// Do UI stuff here
}
});
However, that isn't necessarily thread-safe