Reputation: 2112
I have a widget which needs to do some operations in another thread. It has a method which processes some data and shows the result in a TextView on the widget.
To implement this, I need to call my method in a separate thread. Then I need to include some code to the end of that method to show the results on the widget (something like textView1.setText("my results");
.
This has to be done in a UI thread. I want to use the method runOnUiThread
. But it exists only for an activity. Is there an analog of this method for widget class? What can I do to use that method in my widget?
Here is my code:
public class MyWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds)
{
//...
//here I need to launch a method toBeLaunchedInASeparateThread in a separate thread
}
public void toBeLaunchedInASeparateThread()
{
// ... many operations
int result = 0;
//here I need to launch the following line in the UI thread to follow Android guidelines
setTextToTextView(context, "My result is " + result);
}
public static void setTextToTextView(Context context, String text)
{
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_sample);
views.setTextViewText(R.id.widgetTextViewCard, text);
ComponentName myWidget = new ComponentName(context, MyWidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(manager.getAppWidgetIds(myWidget), views);
}
}
Upvotes: 1
Views: 1153
Reputation: 2311
blackbelt's answer is great, however you can also use textView1.post(runnable)
and methods like that. This way you don't have to create a Handler instance, and the code will run on UI thread. AFAIK both solution will do the exactly same things.
For RemoteViews:
Handler mHandler = new Handler();//this must be ran on the UI thread.
....
mHandler.post(new Runnable(){
public void run() {
toBeLaunchedInASeparateThread();
}
});
Upvotes: 1