我正在研究音乐播放器 - 窗口窗口小部件。.它只需要播放1首歌曲(最好是Mediaplayer Class)。但是我不确定如何实施它。我对Android的开发有所缺乏经验,因此提到了这一点。

到目前为止,我的课程扩展了 AppWidgetProvider, ,我想让本班处理音乐播放部分不是一个好主意,而是一个好主意 Service. 。如果是这样,怎么样?

此外,我有3个按钮:播放,暂停和停止,我可以区分哪个按钮 onReceive(...).

提前致谢!


这是班级。

public class MusicManager extends AppWidgetProvider {

    private final String ACTION_WIDGET_PLAY = "PlaySong";
    private final String ACTION_WIDGET_PAUSE = "PauseSong";
    private final String ACTION_WIDGET_STOP = "StopSong";   
    private final int INTENT_FLAGS = 0;
    private final int REQUEST_CODE = 0;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {

        RemoteViews controlButtons = new RemoteViews(context.getPackageName(),
                R.layout.main);

        Intent playIntent = new Intent(context, MusicService.class);

        Intent pauseIntent = new Intent(context, MusicService.class);

        Intent stopIntent = new Intent(context, MusicService.class);


        PendingIntent playPendingIntent = PendingIntent.getService(
                context, REQUEST_CODE, playIntent, INTENT_FLAGS);
        PendingIntent pausePendingIntent = PendingIntent.getService(
                context, REQUEST_CODE, pauseIntent, INTENT_FLAGS);
        PendingIntent stopPendingIntent = PendingIntent.getService(
                context, REQUEST_CODE, stopIntent, INTENT_FLAGS);

        controlButtons.setOnClickPendingIntent(
                R.id.btnPlay, playPendingIntent);
        controlButtons.setOnClickPendingIntent(
                R.id.btnPause, pausePendingIntent);
        controlButtons.setOnClickPendingIntent(
                R.id.btnStop, stopPendingIntent);

        appWidgetManager.updateAppWidget(appWidgetIds, controlButtons);         
    }
}
有帮助吗?

解决方案

添加 <service android:name=".MusicService" android:enabled="true" />表现出来!

其他提示

在里面 onUpdate(...) 您的方法 AppWidgetProvider, ,使用类似的内容来启动服务(此示例将服务与按钮单击事件相关联):

Intent intent = new Intent(context, MusicService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

// Get the layout for the App Widget and attach an on-click listener to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
views.setOnClickPendingIntent(R.id.button, pendingIntent);

有关更多信息查看 这里

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top