我有一个小部件,它有一个简单的按钮实现。每当我们点击按钮时,它会翻转到给定的一组图像中。现在,如果我想让它每5秒钟翻转一次而不需要点击按钮,应该怎么做呢?
我有一个小部件,它有一个简单的按钮实现。每当我们点击按钮时,它会翻转到给定的一组图像中。现在,如果我想让它每5秒钟翻转一次而不需要点击按钮,应该怎么做呢?
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ACTION_APPWIDGET_UPDATE.equals(action)) {
// Update your widget here.
}
}
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
// send a broadcast to the widget.
}
});
}
};
timer.scheduleAtFixedRate(task, 0, 5000); // Executes the task every 5 seconds.
http://www.parallelrealities.co.uk/2011/09/using-alarmmanager-for-updating-android.html
注意:但是,5秒真的太快了。这会根据你在后台做什么而很快耗尽你的电池。请考虑减少更新频率。
onStartCommand
函数。 - Richard Barraclough //update interval for widget
val UPDATE_INTERVAL = 1000L
//Handler to repeat update
private val updateWidgetHandler = Handler()
//runnable to update widget
private var updateWidgetRunnable: Runnable = Runnable {
run {
//Update Widget
sendUpdateBroadcast()
// Re-run it after the update interval
updateWidgetHandler.postDelayed(updateWidgetRunnable, UPDATE_INTERVAL)
}
}
private fun sendUpdateBroadcast() {
val updateWidgetIntent = Intent(this, YourWidget::class.java)
updateWidgetIntent.action = ACTION_APPWIDGET_UPDATE
val ids = AppWidgetManager.getInstance(application)
.getAppWidgetIds(ComponentName(application, YourWidget::class.java))
updateWidgetIntent.putExtra(EXTRA_APPWIDGET_IDS, ids)
sendBroadcast(updateWidgetIntent)
}
// START updating in foreground
override fun onResume() {
super.onResume()
updateWidgetHandler.postDelayed(updateWidgetRunnable, UPDATE_INTERVAL)
}
// REMOVE callback if app in background
override fun onPause() {
super.onPause()
// uncomment to pause updating widget when app is in Background
// updateWidgetHandler.removeCallbacks(updateWidgetRunnable);
}
onReceive
方法,像这样:最初的回答。override fun onReceive(context: Context, intent: Intent) {
if (ACTION_APPWIDGET_UPDATE == intent.action) {
// Update your widget here.
val remoteViews =
RemoteViews(
context.packageName,
R.layout.your_widget
)
// Update Text and images
updateViews(remoteViews)
//Apply Update
AppWidgetManager.getInstance(context).updateAppWidget(
ComponentName(context, ComWidget::class.java)
, remoteViews)
}
}
onReceive
中启动计时器,因为这会在操作系统每次发送更新请求到小部件时启动一个新的计时器。 - Richard BarracloughTimer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
}, 5000, 5000);
第一个变化将在5秒后发生。
bitmap
来自哪里? - Richard Barraclough