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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With