Как обновить виджет приложения Glance внутри службы в Android или за пределами GlanceAppWidgetAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Как обновить виджет приложения Glance внутри службы в Android или за пределами GlanceAppWidget

Сообщение Anonymous »

В Android 12 представлен новый API для создания виджетов приложений под названием Glance. Мой вариант использования: у меня есть кнопка внутри компонуемого Glance, и при нажатии вызывается служба переднего плана, которая извлекает данные с сервера и обновляет виджет. В устаревшем API мы можем выполнить обновление, создав новые удаленные представления и обновив виджет через диспетчер виджетов приложения, как показано ниже.
class COVIDSummaryUpdateService : Service() {
private val TAG = "COVIDSummaryUpdateService"
private val FOREGROUND_SERVICE_ID = 111

override fun onBind(intent: Intent?): IBinder? {
return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startNotificationForForeground()
val views = RemoteViews(
[email protected],
R.layout.covid_summary_layout
)
views.setViewVisibility(R.id.ivRefresh, View.GONE)
views.setViewVisibility(R.id.progressBar, View.VISIBLE)
val componentName = ComponentName(
[email protected],
COVIDSummaryAppWidgetProvider::class.java
)
val manager =
AppWidgetManager.getInstance([email protected])
manager.updateAppWidget(componentName, views)

COVIDApiService.getCOVIDApi().getSummary()
.enqueue(object : Callback {
override fun onResponse(
call: Call,
response: Response
) {
if (response.isSuccessful && response.code() == 200) {
updateWidgetWithResponse(response.body())
} else {
hideProgressView()
}
stopService()
}

override fun onFailure(call: Call, t: Throwable) {
t.message?.let { Log.d(TAG, it) }
hideProgressView()
stopService()
}
})
return START_STICKY
}

private fun stopService() {
stopForeground(true)
stopSelf()
}

private fun updateWidgetWithResponse(summaryResponse: SummaryResponse?) {
try {
summaryResponse?.let {
val views = RemoteViews(
[email protected],
R.layout.covid_summary_layout
)
views.setTextViewText(
R.id.tvNewConfirmedCases,
"${summaryResponse.global.newConfirmed}"
)
views.setTextViewText(
R.id.tvNewDeaths,
"${summaryResponse.global.newDeaths}"
)
views.setTextViewText(
R.id.tvNewRecovered,
"${summaryResponse.global.newRecovered}"
)
views.setTextViewText(
R.id.tvTotalConfirmedCases,
"${summaryResponse.global.totalConfirmed}"
)
views.setTextViewText(
R.id.tvTotalDeaths,
"${summaryResponse.global.totalDeaths}"
)
views.setTextViewText(
R.id.tvTotalRecovered,
"${summaryResponse.global.totalRecovered}"
)
views.setViewVisibility(R.id.ivRefresh, View.VISIBLE)
views.setViewVisibility(R.id.progressBar, View.GONE)
val componentName = ComponentName(
[email protected],
COVIDSummaryAppWidgetProvider::class.java
)
val manager =
AppWidgetManager.getInstance([email protected])
manager.updateAppWidget(componentName, views)
}
} catch (e: Exception) {
e.message?.let { Log.d(TAG, it) }
hideProgressView()
stopService()
}
}

private fun hideProgressView() {
val views = RemoteViews(
[email protected],
R.layout.covid_summary_layout
)
views.setViewVisibility(R.id.ivRefresh, View.VISIBLE)
views.setViewVisibility(R.id.progressBar, View.GONE)
val componentName = ComponentName(
[email protected],
COVIDSummaryAppWidgetProvider::class.java
)
val manager =
AppWidgetManager.getInstance([email protected])
manager.updateAppWidget(componentName, views)
}

private fun startNotificationForForeground() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(
FOREGROUND_SERVICE_ID,
createNotification(
"COVID19Service", "COVID19 Summary Channel",
null,
getString(R.string.foreground_not_text)
)
)
}
}

@RequiresApi(Build.VERSION_CODES.O)
private fun createNotification(
channelId: String,
channelName: String,
contentTitle: String?,
contentText: String,
pendingIntent: PendingIntent? = null
): Notification {
val notificationChannel =
NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE)
notificationChannel.description = channelId
notificationChannel.setSound(null, null)
notificationChannel.lightColor = Color.BLUE
notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE

val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)

return Notification.Builder(this, channelId).let { builder ->
contentTitle?.let {
builder.setContentTitle(contentTitle)
}
builder.setContentText(contentText)
builder.setSmallIcon(R.drawable.ic_covid_19_33)
pendingIntent?.let { builder.setContentIntent(it) }
builder.build()
}
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/706 ... -of-the-gl
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»