gpt4 book ai didi

java - Android简单的小部件

转载 作者:行者123 更新时间:2023-11-30 11:47:45 25 4
gpt4 key购买 nike

我的第一个 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 秒后停止打印时间。如果我只打印没有图像的时间,它会完美地工作,但以这种方式它不会。为什么?

最佳答案

您不能在 BroadcastReceiver 中执行异步操作。 AppWidgetProvider 是一个经过精心设计的 BroadcastReceiver。Android SDK 在接收者生命周期部分提到了这一点:

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

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

关于java - Android简单的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9162339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com