且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的音乐播放器插件

更新时间:2023-02-27 08:19:35

新增<服务机器人:名称=机器人MusicService。:启用=真/> 到清单!

I'm working on a music player-widget (home screen widget).. It only needs to play 1 song, (Preferably with the MediaPlayer class). But I'm not sure how to implement it. I'm kind of inexperienced with Android development, just so that's mentioned.

The class I have so far extends AppWidgetProvider, and I guess it is not a good idea to let this class handle the music-playing part, but rather a Service. And if so, how?

Furthermore, I have 3 buttons: play, pause and stop, and I can distinguish which one has been pressed in onReceive(...).

Thanks in advance!


Here is the class.

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

Added <service android:name=".MusicService" android:enabled="true" /> to the manifest!