【问题标题】:How to update widget Android Studio Kotlin如何更新小部件 Android Studio Kotlin
【发布时间】:2018-03-05 20:58:03
【问题描述】:

我是 Android Studio 的新手,我的问题是我的小部件没有更新。假设我更改了数据 JSON。我已经阅读了一些线程并说小部件的刷新时间间隔为 30 分钟。但我已经等了我的模拟器 30 分钟,没有任何改变。有人可以帮我解决这个问题吗?因为我希望我的小部件默认更新至少 30 分钟..

class TestWidget : AppWidgetProvider() {

    private val httpClient = AsyncHttpClient()
    private var title = String.toString()
    private var imageUrl = String.toString()

    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
        // There may be multiple widgets active, so update all of them

        httpClient.get(jsonUrl, object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out Header>, response: JSONArray) {

                val json = response.getJSONObject(0)
                title = json.getString("title")
                imageUrl = json.getString("imageUrl")

                val views = RemoteViews(context.packageName, R.layout.test_widget)
                views.setTextViewText(R.id.text, title)
                Picasso.with(context)
                        .load(imageUrl)
                        .into(views, R.id.image, appWidgetIds)

            }

            override fun onFailure(statusCode: Int, headers: Array<out Header>?, throwable: Throwable?, errorResponse: JSONObject?) {
                println(throwable?.localizedMessage)

            }
        })

        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)

        }
    }

    override fun onEnabled(context: Context) {
        // Enter relevant functionality for when the first widget is created
    }

    override fun onDisabled(context: Context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    companion object {

        internal fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager,
                                     appWidgetId: Int) {

            // Construct the RemoteViews object
            val views = RemoteViews(context.packageName, R.layout.test_widget)

            // Instruct the widget manager to update the widget
            appWidgetManager.updateAppWidget(appWidgetId, views)
        }
    }
}

【问题讨论】:

标签: android android-widget kotlin


【解决方案1】:

哦,我想我已经找到了解决方案。 我的小部件信息 XML 上有一个 android:updatePeriodMillis。这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2011-02-14
    • 2012-12-17
    相关资源
    最近更新 更多