我正在编写一个应用程序小部件,它从服务器获取数据并将其显示在appwidget中。
问题是,当没有互联网连接时,此时系统会更新小部件,TextView
文本值重置为使用android:text="sometext"
设置的默认文本
就像这样:
TextView
TextView
中的上一个文字重置为android:text=""
我知道在某个地方我做错了什么,因为在没有连接互联网的其他小部件(不是我的)中没有重置。
文件 WidgetProvider.java
public class WidgetProvider extends AppWidgetProvider {
public static String LOG_TAG = "MYAPPLOG";
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d(LOG_TAG, "onReceive");
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
Log.d(LOG_TAG, "onUpdate");
for (int widgetID : appWidgetIds)
{
updateWidget(context, widgetID);
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
Log.d(LOG_TAG, "onDeleted");
}
public void updateWidget(Context context, int widgetID)
{
context.startService(new Intent(context, UpdatingService.class).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID));
}
}
文件 UpdatingService.java
public class UpdatingService extends IntentService {
public static String LOG_TAG = "MYAPPLOG";
public UpdatingService() {
super("UpdatingService");
}
@Override
protected void onHandleIntent(Intent intent) {
// getting widgetID from intent and other vars
RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(),
R.layout.initial_layout);
if(isConnected(getApplicationContext()))
{
String response = getServerResponse();
if(response != null)
{
try {
JSONObject JSON = new JSONObject(response);
// get data from server
// ...
// set values to the views
remoteViews.setTextViewText(R.id.textView, someText);
} catch (JSONException e) {
e.printStackTrace();
Log.d(LOG_TAG, "JSONObject failed");
}
}
else
{
// LOG: error connection to server
}
}
else
{
// LOG: No internet connection
}
// updating apwidget (set click action for the some button)
// if not do update then button will not work
Intent someIntent = new Intent(getApplicationContext(), WidgetProvider.class);
someIntent.setAction(WidgetProvider.ACTION_GOTO);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
widgetID, someIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.goToLayout, pendingIntent);
AppWidgetManager.getInstance(getApplicationContext().getApplicationContext())
.updateAppWidget(widgetID, remoteViews);
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
return true;
}
return false;
}
public String getServerResponse() {
// using HttpURLConnection
}
}
我希望得到你的帮助或提示。我写了几个小部件,但都有这个问题。非常感谢你的关注。
答案 0 :(得分:0)
当AppWidget更新发生时,必须设置每个属性,就像文本视图的所有值,所有单击侦听器,颜色等一样。未设置的内容将使用布局XML中的默认值。
在你的情况下,你在else分支中没有做任何事情(“没有互联网”),因此你的app小部件以默认文本结束。因此,当您从服务器获取数据时,您必须将其保存并在下次没有互联网连接时使用它。