Reputation: 213
I have a problem with my first android widget... I am doing like this:
public class TestwidActivity extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 1000);
}
@Override
public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
super.onReceive(context, intent);
}
}
private class MyTime extends TimerTask {
RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;
java.text.DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM,Locale.getDefault());
public MyTime(Context context, AppWidgetManager appWidgetManager) {
this.appWidgetManager = appWidgetManager;
remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
thisWidget = new ComponentName(context, TestwidActivity.class);
}
@Override
public void run() {
Bitmap bm;
remoteViews.setTextViewText(R.id.Clock,
"Time = " + format.format(new Date()));
bm= BitmapFactory.decodeFile("/sdcard/myFile.png");
remoteViews.setImageViewBitmap(R.id.team11, bm);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}
}
but this stops printing the time after 2 seconds. If I only print the time without the image it works perfect, but in this way it doesn't.why?
Upvotes: 2
Views: 294
Reputation: 321
You cannot do asynchronous stuff in a BroadcastReceiver. AppWidgetProvider is a pimped BroadcastReceiver. The Android SDK mentions this in the Rceiver Lifecycle section:
"This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes."
http://developer.android.com/reference/android/content/BroadcastReceiver.html#ReceiverLifecycle
Upvotes: 1