前提・実現したいこと
ネットワークから取得したデータを、widgetに表示したいです。
流れ
・widgetの更新ボタンをタップ
・worker managerでサーバーからデータ取得
・worker managerのデータ取得完了後、widgetのstaticメソッドからwidgetを更新
・正常に更新完了
・5秒ほどたつと、widgetが更新前の初期画面になる
発生している問題・エラーメッセージ
・正常に更新完了
・5秒ほどたつと、widgetが更新前の初期画面になる
が行われたあと、onUpdateが動作し、初期化されている
該当のソースコード
xml
1<?xml version="1.0" encoding="utf-8"?> 2<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" 3 android:initialKeyguardLayout="@layout/widget" 4 android:initialLayout="@layout/widget" 5 android:minWidth="320dp" 6 android:minHeight="40dp" 7 android:previewImage="@drawable/example_appwidget_preview" 8 android:resizeMode="horizontal|vertical" 9 android:updatePeriodMillis="86400000" 10 android:widgetCategory="home_screen|keyguard"></appwidget-provider>
kotlin
1class Widget : AppWidgetProvider() { 2 override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { 3 Util.log.d("onUpdate") 4 5 // There may be multiple widgets active, so update all of them 6 for (appWidgetId in appWidgetIds) { 7 update(context, appWidgetManager, appWidgetId) 8 } 9 } 10 companion object { 11 internal fun update(context: Context, appWidgetManager: AppWidgetManager, 12 appWidgetId: Int) { 13 // Construct the RemoteViews object 14 val views = RemoteViews(context.packageName, R.layout.widget) 15 16 // 各クリックevent 17 views.setOnClickPendingIntent(R.id.widget_button_refresh 18 , PendingIntent.getBroadcast( 19 context 20 , createRequestCode(appWidgetId, ClickType.UPDATE_START) 21 , createIntent(context, appWidgetId, ClickType.UPDATE_START) 22 , PendingIntent.FLAG_UPDATE_CURRENT)) 23 24 // Instruct the widget manager to update the widget 25 appWidgetManager.updateAppWidget(appWidgetId, views) 26 } 27 28 // worker managerから起動 29 private fun updateEnd(context: Context, appWidgetId: Int) { 30 Util.log.d("updateEnd") 31 reDisplay(context, appWidgetId) 32 } 33 34 private fun reDisplay(context:Context, appWidgetId:Int, position:Int = 0){ 35 Util.log.d("reDisplay") 36 37 val views = RemoteViews(context.packageName, R.layout.widget) 38 views.setTextViewText(R.id.widget_text_article, "DBから取得したデータ") 39 40 AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, views) 41 } 42 43 private fun createRequestCode(appWidgetId: Int, type: ClickType): Int{ 44 return appWidgetId * ClickType.values().size + type.ordinal 45 } 46 private fun createIntent(context: Context, appWidgetId: Int, type: ClickType): Intent{ 47 return Intent(context, Widget::class.java).apply { 48 putExtra(APP_WIDGET_ID, appWidgetId) 49 putExtra(CLICK_TYPE, type) 50 } 51 } 52 } 53} 54
試したこと
onUpdate、Companion.updateの中身を最低限減らしましたが、変わりませんでした。
補足情報(FW/ツールのバージョンなど)
android studio 3.3.0
kotlin 1.3.20
android os 8.0.0
あなたの回答
tips
プレビュー