如何解决当onDatasetChanged方法包含异步网络调用Android时,小部件ListView不刷新的问题?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (1182)

有已下代码:

CarsWidgetProvider

class CarsWidgetProvider : AppWidgetProvider() {
    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
        Log.d("CAR_LOG", "Updating")
        val widgets = appWidgetIds.size

        for (i in 0 until widgets) {
            Log.d("CAR_LOG", "Updating number $i")
            val appWidgetId = appWidgetIds[i]

            // Get the layout
            val views = RemoteViews(context.packageName, R.layout.widget_layout)
            val otherIntent = Intent(context, ListViewWidgetService::class.java)
            views.setRemoteAdapter(R.id.cars_list, otherIntent)

            // Set an onclick listener for the action and the refresh button
            views.setPendingIntentTemplate(R.id.cars_list, getPendingSelfIntent(context, "action"))
            views.setOnClickPendingIntent(R.id.refresh, getPendingSelfIntent(context, "refresh"))

            // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, views)
        }
    }

    private fun onUpdate(context: Context) {
        val appWidgetManager = AppWidgetManager.getInstance(context)
        val thisAppWidgetComponentName = ComponentName(context.packageName, javaClass.name)
        val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidgetComponentName)
        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.cars_list)
        onUpdate(context, appWidgetManager, appWidgetIds)
    }

    private fun getPendingSelfIntent(context: Context, action: String): PendingIntent {
        val intent = Intent(context, javaClass)
        intent.action = action
        return PendingIntent.getBroadcast(context, 0, intent, 0)
    }

    @SuppressLint("CheckResult")
    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)
        if (context != null) {
            if ("action" == intent!!.action) {
                val car = intent.getSerializableExtra("car") as Car

                // Toggle car state
                Api.toggleCar(car)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe {
                            Log.d("CAR_LOG", "We've got a new state: $it")
                            car.state = it
                            onUpdate(context)
                        }

            } else if ("refresh" == intent.action) {
                onUpdate(context)
            }
        }
    }
}

ListViewWidgetService

class ListViewWidgetService : RemoteViewsService() {
    override fun onGetViewFactory(intent: Intent): RemoteViewsService.RemoteViewsFactory {
        return ListViewRemoteViewsFactory(this.applicationContext, intent)
    }
}

internal class ListViewRemoteViewsFactory(private val context: Context, intent: Intent) : RemoteViewsService.RemoteViewsFactory {
    private var cars: ArrayList<Car> = ArrayList()

    override fun onCreate() {
        Log.d("CAR_LOG", "Oncreate")
        cars = ArrayList()
    }

    override fun getViewAt(position: Int): RemoteViews {
        val remoteViews = RemoteViews(context.packageName, R.layout.widget_list_item_car)

        // Get the current car
        val car = cars[position]
        Log.d("CAR_LOG", "Get view at $position")
        Log.d("CAR_LOG", "Car: $car")

        // Fill the list item with data
        remoteViews.setTextViewText(R.id.title, car.title)
        remoteViews.setTextViewText(R.id.description, car.model)
        remoteViews.setTextViewText(R.id.action, "${car.state}")
        remoteViews.setInt(R.id.action, "setBackgroundColor",
                if (car.state == 1) context.getColor(R.color.colorGreen) else context.getColor(R.color.colorRed))

        val extras = Bundle()
        extras.putSerializable("car", car)

        val fillInIntent = Intent()
        fillInIntent.putExtras(extras)

        remoteViews.setOnClickFillInIntent(R.id.activity_chooser_view_content, fillInIntent)
        return remoteViews
    }

    override fun getCount(): Int {
        Log.d("CAR_LOG", "Counting")
        return cars.size
    }

    @SuppressLint("CheckResult")
    override fun onDataSetChanged() {
        Log.d("CAR_LOG", "Data set changed")

        // Get a token
        Api.getToken()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { token ->
                    if (token.isNotEmpty()) {
                        Log.d("CAR_LOG", "Retrieved token")
                        DataModel.token = token

                        // Get the cars
                        Api.getCars()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe {
                                    cars = it as ArrayList<Car>

                                    Log.d("CAR_LOG", "Found cars: $cars")
                                }
                    } else {
                        Api.getCars()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe {
                                    cars = it as ArrayList<Car>

                                    Log.d("CAR_LOG", "Found cars: $cars")
                                }
                    }
                }
    }

    override fun getViewTypeCount(): Int {
        Log.d("CAR_LOG", "Get view type count")
        return 1
    }

    override fun getItemId(position: Int): Long {
        Log.d("CAR_LOG", "Get item ID")
        return position.toLong()
    }

    override fun onDestroy() {
        Log.d("CAR_LOG", "On Destroy")
        cars.clear()
    }

    override fun hasStableIds(): Boolean {
        Log.d("CAR_LOG", "Has stable IDs")
        return true
    }

    override fun getLoadingView(): RemoteViews? {
        Log.d("CAR_LOG", "Get loading view")
        return null
    }
}

数据模型

object DataModel {
    var token: String = ""
    var currentCar: Car = Car()
    var cars: ArrayList<Car> = ArrayList()

    init {
        Log.d("CAR_LOG", "Creating data model")
    }

    override fun toString(): String {
        return "Token : $token \n currentCar: $currentCar \n Cars: $cars"
    }
}

class Car : Serializable {
    var id : String = ""
    var title: String = ""
    var model: String = ""
    var state: Int = 0
}
cars = GetCars().execute().get() as ArrayList<Car>

class GetCars : AsyncTask<String, Void, List<Car>>() {
    override fun doInBackground(vararg params: String?): List<Device> {
        return Api.getCars().blockingFirst();
    }
}
提问于
用户回答回答于

问题似乎在于异步请求,刷新视图.onDataSetChanged()就能完成

热门问答

Tencent iot-sdk-embedded-c在Windows下编译出错:无法解析外部符号?

无聊至极互联网重度用户
推荐已采纳

智能钛机器学习平台的模型怎么从外部调用?

腾讯智能钛AI开发者

腾讯云 · 智能钛产品团队 (已认证)

腾讯智能钛产品团队官方运营账号。分享产品最新动态,第一时间解答用户疑问。
推荐

腾讯云IM调用 add_group_member提示该群不能邀请成员?

推荐已采纳
是什么类型的群?根据相应类型的邀请他人入群的控制项,对照文档看下是否允许邀请他人入群。 参考文档:https://cloud.tencent.com/document/product/269/1502#.E7.BE.A4.E6.88.90.E5.91.98.E6.93.8D.E4...... 展开详请

负载均衡监听器绑定云服务器,其端口状态为异常是什么原因造成的呢?

HappyLau谈云计算

腾讯云 · 云计算高级工程师 (已认证)

专注于公有云,私有云解决方案,在kubernetes,openstack,kvm,ceph,linux,shell有丰富的实战经验。
推荐
端口异常说明是健康检查异常,可以按照如下步骤进行排查: 1. 确保后端RS端口或服务可以正常访问,可以通过curl(七层)或者telnet(四层)测试外网是否可以访问,如果不可访问检查web服务器配置,防火墙和安全组设置; 2. 确保安全组中放行了CLB的VIP,健康检查探测是通...... 展开详请

在小程序开通直播功能,是不是还需要业务去申请直播的证书?

推荐
腾讯云有商业直播方案(提供小程序直播插件),客户通过直播插件实现直播业务(不需额外提供直播资质) 插件对接条件: 客户小程序类目为“电商平台”或“在线教育” 所以就是说, 只要用了腾讯云的小程序直播方案, 小程序的类目为 “电商平台” 或“ 在线教育”, 就可以。只要自身业务不...... 展开详请

腾讯云 TRTC 互动直播 云直播 商业直播区别是什么?

人生的旅途辣鸡前端
推荐
云直播:腾讯云的直播云端处理分发平台 移动直播:腾讯云提供的直播推拉流集成的sdk(iOS、Android、小程序) 互动直播:云直播(云端)+移动直播(终端)+连麦功能 商业直播:基于云直播的直播小程序插件(SaaS腾讯云提供页面模板,PaaS客户自己开发) 商业直播和移动直播...... 展开详请

所属标签

扫码关注云+社区

领取腾讯云代金券