我从用户那里获取数据并存储到数据库中。我的数据库只有一个值。因此,每次用户进入数据库时,数据库都会更新。我在AppWidget的文本视图中显示这些数据。我使用此代码:
public void onUpdate(Context context, android.appwidget.AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//Get all ids
ComponentName thisWidget = new ComponentName(context.getPackageName(),SmsSchedulerWidget.class.getName());
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
//the datas to be shown are fetched from the database
DatabaseManager dbManager = new DatabaseManager(context);
dbManager.open();
contactNumber = dbManager.fetchContactNumber();
Log.i("contactNumber",contactNumber);
date = dbManager.fetchDate();
Log.i("date",date);
message = dbManager.fetchMessage();
Log.i("message",message);
status = dbManager.fetchStatus();
Log.i("status", status);
dbManager.closeDatabase();
//Build the intent to call the service
//it creates the UI for the given app widget
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.schdulesms_appwidget_layout);
remoteViews.setTextViewText(R.id.to_appwidget_saved_data,
contactNumber);
remoteViews.setTextViewText(R.id.date_appwidget_saved_data, date);
remoteViews.setTextViewText(R.id.status_appwidget_saved, status);
remoteViews.setTextViewText(R.id.message_appwidgset_saved_data,
message);
//to start the activity with the click on the layout
Intent clickIntent = new Intent(context.getApplicationContext(),MainActivity.class);
clickIntent.setFlags(clickIntent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent= PendingIntent.getActivity(context, 0, clickIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.full_widget, pendingIntent);
//to update the BroadCast Receiver so that it holds the current values in the layout
Intent updateIntent =new Intent(context,SmsSchedulerWidget.class);
updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
updateIntent.setComponent(thisWidget);
PendingIntent pendingIntentForUpdate = PendingIntent.getBroadcast(context, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.logoBtn, pendingIntentForUpdate);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
我的应用小部件应该在按钮单击后自动更新,并且用户在运行时已将新值输入到数据库中。但是应用小部件仅在从屏幕上卸载appwidget然后再次安装或者再次安装后自行更新该程序重新运行。为什么会发生这种情况?单击按钮?????
后如何更新我的应用小部件答案 0 :(得分:1)
要手动更新AppWidget
,您必须先发送Broadcast
,然后使用AppWidgetProvider
的{{1}}方法接收onReceive()
。从onReceive()
开始,您应该从广播Intent
中提取所需的所有值,然后手动调用onUpdate()
方法。希望这会有所帮助。