gpt4 book ai didi

Android 在 Volley 服务后更新 AppWidget

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:11:02 25 4
gpt4 key购买 nike

我的小部件的配置 Activity 启动了一个服务来发出 http 请求并更新小部件 View 。我可以很好地从服务更新 View (见下文),但为什么我不能从响应处理程序更新它们?

public class TestService extends Service {

@SuppressWarnings("unused")
private static final String TAG = "TestService";

@Override
public void onCreate() {
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service started");

final Context context = this;
final RemoteViews views = new RemoteViews(getPackageName(), R.layout.widget_activity);
final ComponentName thisWidget = new ComponentName(context, WidgetActivity.class);

final RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://google.com";

final AppWidgetManager manager = AppWidgetManager.getInstance(context);
final int[] ids = manager.getAppWidgetIds(thisWidget);

StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {

// DOES NOT WORK
views.setTextViewText(R.id.last_updated_text, "After Request");
manager.partiallyUpdateAppWidget(ids, views);

// ALSO DOES NOT WORK
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
views.setTextViewText(R.id.last_updated_text, "After Request");
manager.partiallyUpdateAppWidget(ids, views);
}
});

// ALSO DOES NOT WORK
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
views.setTextViewText(R.id.last_updated_text, "After Request");
AppWidgetManager.getInstance(context).updateAppWidget(thisWidget, views);
}
});

}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
);

queue.add(request);

// WORKS
views.setTextViewText(R.id.last_updated_text, "Before Request");
manager.partiallyUpdateAppWidget(ids, views);

return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

}

编辑

我重新启动了我的设备,现在以下似乎工作正常:

StringRequest priceRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Result: " + response);

views.setTextViewText(R.id.last_updated_text, "After Request");
AppWidgetManager.getInstance(context).updateAppWidget(thisWidget, views);

}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
);

最佳答案

您只能使用 UI 线程更新 android View 。

尝试在 UI 线程中更新小部件。

new Handler(Looper.getMainLooper()).post(...runnable)

关于Android 在 Volley 服务后更新 AppWidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51150218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com