android виджет погоды + asynctask
сделал тестовый виджет погоды, но проблема возникла с обновлением информации. то есть получение данных идет в asynktask, а получаю данные я через asynktask.execute.get, то есть по факту пока task не обработается виджет будет висеть. Я так понимаю данные как-то обновлять я должен из onPostExecute, но я не понимаю как мне добраться до экземпляра виджета.
package com.example.widget02;
import android.app.Application;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.RemoteViews;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.SplittableRandom;
import java.util.concurrent.ExecutionException;
public class MyWidget extends AppWidgetProvider {
private static Context contextXZ;
int widgetID = AppWidgetManager.INVALID_APPWIDGET_ID;
Intent resultValue;
private static String LOG_TAG = "myLogs";
public final static String WIDGET_PREF = "widget_pref";
public final static String WIDGET_COLOR = "widget_color_";
public final static String WIDGET_CITY = "widget_city_";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
SharedPreferences sp = context.getSharedPreferences(config.WIDGET_PREF, Context.MODE_PRIVATE);
for (int id : appWidgetIds) {
updateWidget(context, appWidgetManager, sp, id);
}
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
// Удаляем Preferences
SharedPreferences.Editor editor = context.getSharedPreferences(
config.WIDGET_PREF, Context.MODE_PRIVATE).edit();
for (int widgetID : appWidgetIds) {
editor.remove(config.WIDGET_CITY + widgetID);
editor.remove(config.WIDGET_COLOR + widgetID);
}
editor.commit();
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
static void updateWidget(Context context, AppWidgetManager appWidgetManager,
SharedPreferences sp, int widgetID) {
// Читаем параметры Preferences
int widgetcolor = sp.getInt(config.WIDGET_COLOR + widgetID, 0);//ConfigActivity
String widgetCity = sp.getString(config.WIDGET_CITY + widgetID, "Krasnoyarsk");
String url00="https://api.openweathermap.org/data/2.5/weather?q="+widgetCity+"&appid=018a66dd3052ef416e514040a163dfe3&units=metric&lang=ru";
contextXZ=context;
GetUrlData ggg= new GetUrlData();
ggg.execute(url00);
String result="";
String result02="";
try {
result = ggg.get();
JSONObject jsonobj = new JSONObject(result);
result02=
jsonobj.getString("name")+"\n"+
jsonobj.getJSONArray("weather").getJSONObject(0).getString("description")+"\n"+
"Температура "+jsonobj.getJSONObject("main").getDouble("temp")+"\n"
+"Ветер "+jsonobj.getJSONObject("wind").getDouble("speed")+"\n";
Log.d(LOG_TAG, "\n"+result02);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
RemoteViews widgetView = new RemoteViews(context.getPackageName(), R.layout.my_widget);
widgetView.setTextViewText(R.id.tvInformation, result02);
widgetView.setTextColor(R.id.tvInformation, widgetcolor);
// Конфигурационный экран (первая зона) по нажатью
Intent configIntent = new Intent(context, config.class);
configIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID);
PendingIntent pIntent = PendingIntent.getActivity(context, widgetID, configIntent, 0);
widgetView.setOnClickPendingIntent(R.id.tvPressConfig, pIntent);
// Обновление виджета (вторая зона) по нажатию
Intent updateIntent = new Intent(context, MyWidget.class);
updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { widgetID });
pIntent = PendingIntent.getBroadcast(context, widgetID, updateIntent, 0);
widgetView.setOnClickPendingIntent(R.id.tvPressUpdate, pIntent);
// Обновляем виджет
appWidgetManager.updateAppWidget(widgetID, widgetView);
}
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
private static class GetUrlData extends AsyncTask<String,String,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
HttpURLConnection connection =null;
BufferedReader reder= null;
try {
URL url=new URL(strings[0]);
connection= (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reder=new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer=new StringBuffer();
String line="";
while( (line=reder.readLine())!=null )
buffer.append(line).append("\n");
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(connection!=null)connection.disconnect();
if(reder!=null) {
try {
reder.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// RemoteViews widgetView = new RemoteViews(contextXZ.getPackageName(), R.layout.my_widget);
//widgetView.setTextViewText(R.id.tvInformation, s);
// Log.d(LOG_TAG, "city onPostExecute="+s);
}
}
}