简体   繁体   English

如何在主屏幕中自动更新小部件

[英]How to automatically update widget in home screen

I have completed one task application in android.And now i create one widget for this application.In my widget i have display list of task for today,which is working correctly.My problem is when i go to my application and add some task in today and then back to the home screen the widget having only old data instead of new data and no modification...please any one help me.... 我已经在android中完成了一个任务应用程序。现在我为该应用程序创建了一个小部件。在我的小部件中,我有今天任务的显示列表,该列表运行正常。我的问题是当我转到应用程序并在其中添加一些任务时今天,然后返回主屏幕,该窗口小部件仅包含旧数据,而不包含新数据,并且没有修改...请任何人帮我...。

My RemoteFactory class: 我的RemoteFactory类:

public class TaskItemStatus implements RemoteViewsService.RemoteViewsFactory {
Context context;
int appWidgetId;
String statusRemainingTask="false";
String[] items;
private final String TAG = "CalendarViewSample:"
        + this.getClass().getName();

public TaskItemStatus(Context context, Intent intent) {
    this.context = context;
    appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID);
    getData();
}

@SuppressLint("SimpleDateFormat")
private void getData() {
    List<String> listTask=new ArrayList<String>();
    Taskdatabase objTaskDb = new Taskdatabase(this.context);
    objTaskDb.Open();
    Calendar calendarToday = Calendar.getInstance();
    SimpleDateFormat simpledateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String dateToday = simpledateFormat.format(calendarToday.getTime());
    listTask.addAll(objTaskDb.fetchTodayRemainTask(dateToday, statusRemainingTask));
    Log.i(TAG,"ListTask:"+listTask.toString());
    items=new String[listTask.size()];
    items=listTask.toArray(items);
}

@Override
public int getCount() {
    return (items.length);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public RemoteViews getLoadingView() {
    return null;
}
@Override
public RemoteViews getViewAt(int position) {
    RemoteViews row = new RemoteViews(context.getPackageName(),
            R.layout.widgetrow);
    row.setTextViewText(android.R.id.text1, items[position]);
    Intent i = new Intent();
    //Bundle extras = new Bundle();
    //extras.putString(WidgetTaskSchedular.EXTRA_WORD, items[position]);
    //i.putExtras(extras);
    row.setOnClickFillInIntent(android.R.id.text1, i);
    return (row);
}

@Override
public int getViewTypeCount() {
    return 1;
}

@Override
public boolean hasStableIds() {
    return (true);
}

@Override
public void onCreate() {

}

@Override
public void onDataSetChanged() {

}

@Override
public void onDestroy() {

}

}

WidgetProvider: WidgetProvider:

 public class WidgetTaskSchedular extends AppWidgetProvider {
static int ID;
    static final int[] sameid=new int[1]; 
    public static String EXTRA_WORD=
            "com.capsone.testing.calendar.WORD";
@Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        if(intent.getAction().equals("update_widget"))
        {
        Log.i(TAG,"AppWidgetIds:"+ID);


        for(int i=0;i<1;i++)
        {
            sameid[i]=ID;
            Log.i(TAG,"SameId:"+sameid[i]);
            onUpdate(context, AppWidgetManager.getInstance(context),sameid);
        }

        }
    }





    @SuppressWarnings("deprecation")
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
ID=appWidgetIds[i];

         for (int i=0; i<appWidgetIds.length; i++) {
              Log.i("Widget","WidgetId:"+appWidgetIds.length);
              Intent intentWidgetService=new Intent(context, WidgetService.class);
              intentWidgetService.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
              intentWidgetService.setData(Uri.parse(intentWidgetService.toUri(Intent.URI_INTENT_SCHEME)));

              RemoteViews remoteView=new RemoteViews(context.getPackageName(),
                                                  R.layout.widgetlayout);

              remoteView.setRemoteAdapter(appWidgetIds[i], R.id.listWidget,
                                      intentWidgetService);


              Intent clickIntent=new Intent(context, ActionBarActivity.class);
              PendingIntent clickPendingIntent=PendingIntent
                                      .getActivity(context, 0,
                                                    clickIntent,
                                                    PendingIntent.FLAG_UPDATE_CURRENT);
              remoteView.setPendingIntentTemplate(R.id.listWidget, clickPendingIntent);
              ComponentName component=new ComponentName(context,WidgetTaskSchedular.class);
              appWidgetManager.updateAppWidget(component, remoteView);
            }

    }
    }

AppWidgetProvider class: AppWidgetProvider类:

ComponentName component = new ComponentName(context, WidgetTaskSchedular.class);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.listWidget);
appWidgetManager.updateAppWidget(component, remoteView);

RemoteView class: RemoteView类:

@Override
public void onDataSetChanged() {
    // Just copy and paste you getdata() coding here
}

One way to achieve this is when you save the new task in your application just send a broadcast with a custom intent to indicate the change in the underlying database. 实现此目的的一种方法是,将新任务保存在应用程序中时,只需发送带有自定义意图的广播以指示基础数据库中的更改。 Add a receiver to this broadcast in your WidgetTaskSchedular class and in on receive method call the onUpdate method to re-populate data in the widget. 在WidgetTaskSchedular类的此广播中添加一个接收器,并在on receive方法中调用onUpdate方法以重新填充窗口小部件中的数据。 Somewhat like this: 有点像这样:

public void onReceive(Context context, Intent intent) {
    System.out.println("On receive function");
    if (intent.getAction().equals("com.android.myapp.myBroadcast")) {
        System.out.println("There is an update from app ");
        //re populate data or in onUpdate
        onUpdate(context, AppWidgetManager.getInstance(context), IDs);
    }
    super.onReceive(context, intent);
}

PS:Save Ids as a static field or something.I took in the IDs in a static array of integers which I populatedin the onUpdate method,you can also try replacing that part with the following code: RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); PS:将ID保存为静态字段或其他内容。我将ID放入以inUpdate方法填充的静态整数数组中,也可以尝试使用以下代码替换该部分:RemoteViews remoteViews = new RemoteViews(context.getPackageName (),R.layout.widget);

        // Update  - here like for example as below
        remoteViews.setTextViewText(R.id.yourTextID, "My updated text");

        // Trigger widget layout update
        AppWidgetManager.getInstance(context).updateAppWidget(
                new ComponentName(context, Widget.class), remoteViews);

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

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