我的小部件是一个空白的背景,在每个开关之间的两种颜色之间切换,延迟了333ms。起初它可以正常工作,但是在158个开关之后,它停止了切换颜色。问题是,我不依靠update。当我将小部件放在主屏幕上时,一切都在无限的循环中。是什么导致它在158个开关后停止切换?更改这样的背景颜色是否太昂贵了,操作系统会禁用我的小部件?
colorswitchwidget.java:
public class ColorSwitchWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.color_switch_widget);
boolean lightOn = true;
while(true){
try{
Thread.sleep(333);
} catch(InterruptedException e){
}
if (lightOn) {
views.setInt(R.id.RelativeLayout1, "setBackgroundColor", Color.argb(150, 255, 248, 231)); //color 1
lightOn = false;
appWidgetManager.updateAppWidget(appWidgetId, views);
} else {
views.setInt(R.id.RelativeLayout1, "setBackgroundColor", Color.argb(220, 255, 248, 231)); //color 2
lightOn = true;
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
@Override
public void onUpdate(Context context, AppWidgetManager, appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
@Override
public void onEnabled(Context context) {
}
@Override
public void onDisabled(Context context) {
}
}
color_switch_widget_info.xml:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:initialKeyguardLayout="@layout/color_switch_widget"
android:initialLayout="@layout/color_switch_widget"
android:minHeight="40dp"
android:minWidth="40dp"
android:previewImage="@drawable/widget_icon_blink"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen"></appwidget-provider>
小部件工作...只是很长时间。无限循环是一个糟糕的选择吗?
编辑:找到一个不使用thread.sleep()的解决方法。我不确定这是否会引起问题或内存问题,但现在似乎有效。
final Handler myHandler = new Handler();
final Runnable blinkRunnable = new Runnable(){
int lightOff = true;
public void run(){
if(lightOff){
lightOff = false;
views.setInt(R.id.RelativeLayout1, "setBackgroundColor", Color.argb(220, 255, 248, 231)); //light "on"
appWidgetManager.updateAppWidget(appWidgetId, views);
myHandler.postDelayed(this, 333);
} else{
lightOff = true;
views.setInt(R.id.RelativeLayout1, "setBackgroundColor", Color.argb(150, 255, 248, 231)); //light "off"
appWidgetManager.updateAppWidget(appWidgetId, views);
myHandler.postDelayed(this, 333);
}
}
};
//start the loop
myHandler.post(blinkRunnable);
这里的问题是您不在自定义线程上运行它。该方法是从主线程调用的,当您暂停主线程(Thread.sleep()
)时,Android认为该应用程序没有响应。
通过创建新类并让其扩展线程