当运行音乐播放器的服务实际开始播放时更新小部件的 Textview
updating Textview of a widget when a service that runs a music player actually started playing
我编写了一个音乐播放器服务 (MusicPlayer),它接受 2 个输入 1) 播放列表名称和 2) 每个 song/audio 的路径。
一切正常。
我有一个当前显示图像的应用程序小部件。我打算添加一个文本视图,以便显示当前播放的歌曲,并在播放新歌曲时更新。
无法弄清楚如何从服务更新小部件。
有什么方法可以访问小部件以更新所需信息?
当然可以。
widgetProvider 本身就是一个广播接收器。所以为了与小部件通信,您只需要发送一个广播。
Intent intent = new Intent(this,YourWidgetProvider.class);
intent.putExtra("SONG","Your Song");
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
// Use an array and EXTRA_APPWIDGET_IDS instead of
AppWidgetManager.EXTRA_APPWIDGET_ID,
// since it seems the onUpdate() is only fired on that:
int[] ids = {widgetId};
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
sendBroadcast(intent);
在widgetprovider的onReceive方法中,可以提取intent中需要的信息
参考:Programmatically update widget from activity/service/receiver
我编写了一个音乐播放器服务 (MusicPlayer),它接受 2 个输入 1) 播放列表名称和 2) 每个 song/audio 的路径。
一切正常。
我有一个当前显示图像的应用程序小部件。我打算添加一个文本视图,以便显示当前播放的歌曲,并在播放新歌曲时更新。
无法弄清楚如何从服务更新小部件。
有什么方法可以访问小部件以更新所需信息?
当然可以。
widgetProvider 本身就是一个广播接收器。所以为了与小部件通信,您只需要发送一个广播。
Intent intent = new Intent(this,YourWidgetProvider.class);
intent.putExtra("SONG","Your Song");
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
// Use an array and EXTRA_APPWIDGET_IDS instead of
AppWidgetManager.EXTRA_APPWIDGET_ID,
// since it seems the onUpdate() is only fired on that:
int[] ids = {widgetId};
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
sendBroadcast(intent);
在widgetprovider的onReceive方法中,可以提取intent中需要的信息
参考:Programmatically update widget from activity/service/receiver