简体   繁体   English

如何更新依赖于AsyncTask的小部件

[英]How to update a widget that depends on AsyncTask

I am creating a widget that needs to make a network connection to update its information. 我正在创建一个需要建立网络连接以更新其信息的小部件。

I'm pretty much using Android Studio boilerplate template for Widgets, and its onUpdate method comes with this: 我几乎都在为Widgets使用Android Studio样板模板,它的onUpdate方法附带了:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    final int N = appWidgetIds.length;
    for (int i = 0; i < N; i++) {
        updateAppWidget(context, appWidgetManager, appWidgetIds[i]);
    }
}

where updateAppWidget is a static function. 其中updateAppWidget是一个静态函数。

The problem is that I'm making use of AsyncTask to make a network connection, retrieve some data and update the widget's its values: 问题是我正在利用AsyncTask建立网络连接,检索一些数据并更新小部件的值:

private class APIQuery extends AsyncTask<Connection, Integer, String> {

    @Override
    protected String doInBackground(Connection... params) {
     // ...
    }
}

The problem is inside updateAppWidget because if I try to instantiate APIQuery from within updateAppWidget , Android Studio says that I cannot call a non-static method from a static method. 问题出在updateAppWidget因为如果我尝试从updateAppWidget实例化APIQuery ,Android Studio会说我无法从静态方法调用非静态方法。

Based on this answer: 根据这个答案:

calling non-static method in static method in Java 在Java中调用静态方法中的非静态方法

The only way to call a non-static method is by instantiating the class, but if I instantiate APIQuery, then Android says that I have to either make updateAppWidget non-static, or APIQuery static. 调用非静态方法的唯一方法是实例化类,但如果我实例化APIQuery,那么Android说我必须使updateAppWidget非静态或APIQuery静态。

What is the right way to approach this situation? 解决这种情况的正确方法是什么? I'm new to Java and Android development, and learning as I go. 我是Java和Android开发的新手,在我学习的过程中学习。

您可以尝试从异步任务的onPostExecute方法更新窗口小部件,也可以使用广播接收器向托管活动发送信号以更新窗口小部件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM