我试图在App小部件中显示不确定的进度条2秒(作为数据刷新的指示)。但是小部件没有显示出来。我尝试使用Handler.postdelayed和Thread.sleep。这两种方法都不起作用。小部件根本没有显示出来。
在小部件布局中
<ProgressBar
style="?android:attr/progressBarStyleLargeInverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/widget_progress_bar"
android:layout_centerInParent="true"
android:indeterminate="false" />
我甚至尝试使用StyleHorizontal作为条形样式。
在AppWidgetProvider类中
我在updateAppWidget()方法的开头调用它:
方法1:新主题
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
final RemoteViews widgetView = new RemoteViews(context.getPackageName(), R.layout.widget_wifi_info_basic);
new Thread(new Runnable() {
int progress = 0;
Handler progressHandler = new Handler();
public void run() {
long timerEnd = System.currentTimeMillis() + 3 * 1000;
while (timerEnd > System.currentTimeMillis() ) {
progress = (int) (timerEnd - System.currentTimeMillis()) / 300;
// Update the progress bar
progressHandler.post(new Runnable() {
public void run() {
widgetView.setProgressBar(R.id.widget_progress_bar,3000,progress,false);
Log.d("tag", "progress=" +progress);
}
});
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Log.w("tag","Progress thread cannot sleep");
}
}
}
}).start();
...
...
}
方法2:CountdownTimer(同样在同一方法内)
widgetView.setViewVisibility(R.id.widget_progress_bar,View.VISIBLE);
new CountDownTimer(2000, 100) {
@Override
public void onTick(long millisUntilFinished) {
//this will be done every 1000 milliseconds ( 1 seconds )
int progress = (2000 - (int)millisUntilFinished) / 100;
widgetView.setProgressBar(R.id.widget_progress_bar,2000,progress,false);
Log.d(Constants.APP_NAME, "progress=" +progress);
}
@Override
public void onFinish() {
//the progressBar will be invisible after 2 seconds
widgetView.setViewVisibility(R.id.widget_progress_bar,View.INVISIBLE);
}
}.start();
方法3:尝试使用不确定的进度条;线程睡眠
// sleep for few seconds
try {
// Show progress bar
widgetView.setViewVisibility(R.id.widget_progress_bar, View.VISIBLE);
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.w("tag","Progress thread cannot sleep");
}
// Hide progress bar
widgetView.setViewVisibility(R.id.widget_progress_bar, View.INVISIBLE);
令人惊讶的是,日志消息(用于打印进度)永远不会被打印出来!?
答案 0 :(得分:0)
为进度条创建单独的线程,然后运行2秒钟。