我的主屏幕上有一个小部件,负责显示当前的歌曲,并能够切换歌曲等...目前我只是想实现它显示当前歌曲的能力。
我附上了所有相关代码......附有评论。没有任何错误,它会更新,但只有当我在HOMESCREEN创建一个新的WIDGET实例时。为了解释我是否有一个小部件,我在开始播放歌曲之前放在那里,当我从我的应用程序开始播放一首歌时它会说“不播放”它会更新但仍会继续说“不播放”然后我创建一个相同类型的新小部件并放下它将保留更新的信息,而旧的小部件仍然会说不玩。如果我改变了歌曲,我所放置的歌曲将不会更新也不会继续播放,也不会创建新歌曲的人会显示更新......
MainActivity从MusicManager接收来电并发送小部件更新(有效吗?)
public static MusicManager myInstance;
private boolean songHasChanged;
public MusicManager(MediaplayerUpdateInterface inter) {
this.player = new MediaPlayer();
this.uiUpdateInterface = inter;
executorService.submit(new Runnable() {
@Override
public void run() {
while (true) {
if(songHasChanged) {
uiUpdateInterface.updateUI(10);
songHasChanged = false;
}
if (player.isPlaying()) {
uiUpdateInterface.updateUI(0);
}
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
public static MusicManager getInstance(MediaplayerUpdateInterface inter) {
if (myInstance == null)
return myInstance = new MusicManager(inter);
else
return myInstance;
}
MusicManager发送更新(Works)
public class TrinityWidget extends AppWidgetProvider {
public static boolean needsImage;
public static final int widgetId = 188772;
@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]);
}
}
// the below method is where it updates i believe it does work but the updates don't apply until A new widget is created?
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
try {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.trinity_widget);
if (MusicManager.myInstance != null) {
views.setTextViewText(R.id.widgetsongtext, MusicManager.myInstance.getCurrentSongInfo() != null ? MusicManager.myInstance.getCurrentSongInfo().getName() : "Not Playing");
views.setTextViewText(R.id.widgetartisttext, MusicManager.myInstance.getCurrentSongInfo() != null ? MusicManager.myInstance.getCurrentSongInfo().getArtist() : "Not Playing");
} else {
views.setTextViewText(R.id.widgetsongtext, "Not Playing");
views.setTextViewText(R.id.widgetartisttext, "Not Playing");
}
appWidgetManager.updateAppWidget(appWidgetId, views);
}catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onEnabled(Context context) {
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
小工具代码(有问题?)
{{1}}
基本上看起来所有小部件都不会更新,直到我手动重新创建它们。他们新的更新。
答案 0 :(得分:0)
问题在于我由于某种原因没有更新正确的ID ......无论哪种方式,我现在都根据课程更新。如下所示
ComponentName projectWidget = new ComponentName(context, TrinityWidget.class);
appWidgetManager.updateAppWidget(projectWidget, views);