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

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

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

有已下代码:

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();
    }
}
提问于
用户回答回答于

这样试试:

@SuppressLint("CheckResult")
override fun onDataSetChanged() {
    Log.d("onDataSetChanged", "------- START ----------")
    // your api call.
    Log.d("onDataSetChanged", "------- END ------------");
}
用户回答回答于

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

扫码关注云+社区

领取腾讯云代金券