应用关闭时,使用服务更新小部件

时间:2015-02-16 13:55:16

标签: java android service widget

我的应用程序中有一个小部件,但我必须在应用关闭时从TextView更新其service

这是我的小部件:



public class Widget extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {
            updateAppWidget(context, appWidgetManager, appWidgetIds[i]);

            Log.i("onUpdate","onUpdate");
        }
    }


    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
        Log.i("onEnable","onEnable");

    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
        Log.i("onDisabled","ondisabled");
    }

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {
        
        
        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);

        Log.i("onUpdateAppWidget","onUpdateAppWidget");


        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }


}
&#13;
&#13;
&#13;

我必须每秒更新一次

2 个答案:

答案 0 :(得分:0)

我在评论中提供的教程和文档链接非常简单,可以在Android中实现简单的服务。 完成后,您可以在服务中运行CountDownTimer。恕我直言,CounDownTimer是迄今为止最好的工具,每秒都可以实现它。它提供了一个简单的onTick方法,每秒调用一次,直到你停止计时器。

public void onTick(long millisUntilFinished) {
                    updateWidget();
                }

答案 1 :(得分:0)

答案很简单。在你的服务类中通过广播将数据发送到widget类,并在你的widget类中注册onUpdate内部的广播接收器并实现BroadcastReceiver类。里面的广播接收器类更新你的文字,我的意思是把你的远程视图和manager.updateAppWidget(thisWidget,remoteViews); 。你完成了!

相关问题