Android简单小部件

时间:2012-02-06 15:18:45

标签: java android

我的第一个Android小部件有问题......我这样做:

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);
        }
    }
}

但是这会在2秒后停止打印时间。如果我只在没有图像的情况下打印时间,那么它的工作原理很完美,但这样做并不合适。

1 个答案:

答案 0 :(得分:1)

您无法在BroadcastReceiver中执行异步操作。 AppWidgetProvider是一个拉皮条的BroadcastReceiver。 Android SDK在Rceiver生命周期部分中提到了这一点:

“这对你在onReceive(Context,Intent)实现中可以做的事情有重要的影响:任何需要异步操作的东西都不可用,因为你需要从函数返回来处理异步操作,但是指出BroadcastReceiver不再处于活动状态,因此系统可以在异步操作完成之前自由终止其进程。“

http://developer.android.com/reference/android/content/BroadcastReceiver.html#ReceiverLifecycle