7

我正在开发一个音乐播放器小部件(主屏幕小部件)。它只需要播放一首歌曲,(最好使用 MediaPlayer 类)。但我不确定如何实现它。我对Android开发有点缺乏经验,所以提到了这一点。

到目前为止我的课程 extends 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);         
    }
}
4

2 回答 2

4

添加<service android:name=".MusicService" android:enabled="true" /> 到清单中!

于 2010-11-29T00:24:17.423 回答
0

In the onUpdate(...) method of your AppWidgetProvider, use something like this to start a service (this example associates the service to a button click event):

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);

For more info look here

于 2010-11-28T21:41:21.603 回答