如何在窗口小部件提供程序中的onReceive方法中更新TextView

时间:2014-02-26 10:59:41

标签: android android-widget

来源:

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    String s = "MusicPlayer";
    if (MusicPlayerActivity.currentActivity != null) {
        s = MusicPlayerActivity.currentActivity.getCurrentTrackName();
    } else {
        Log.d(MusicPlayerActivity.TAG,"STARTING ACTIVITY FROM WIDGET");
        Intent intent1 = new Intent(context, MusicPlayerActivity.class);
        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
    }
    // I WANT TO UPDATE TEXT VIEW HERE
    if (MusicPlayerActivity.currentActivity != null)
        if (intent.getAction().equals(ACTION_WIDGET_NEXT)) {
            MusicPlayerActivity.currentActivity.playNext();
        } else if (intent.getAction().equals(ACTION_WIDGET_PLAY)) {
            MusicPlayerActivity.currentActivity.playPause();
        } else if (intent.getAction().equals(ACTION_WIDGET_PREV)) {
            MusicPlayerActivity.currentActivity.playPrevious();
        }
}

我尝试了这段代码:

Log.d(MusicPlayerActivity.TAG,s);
    remoteViews.setTextViewText(R.id.w_trackInfo, s);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.w_trackInfo);

但如果我把它放在评论位置,这不起作用。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:7)

找到解决方案只需将其添加到评论位置:

RemoteViews views = new RemoteViews(context.getPackageName(),
            R.layout.widget_layout);
    views.setTextViewText(R.id.w_trackInfo, s);
    AppWidgetManager.getInstance(context).updateAppWidget(
            new ComponentName(context, MusicWidgetProvider.class),views);