I'm learning about android services. I have a button in my main activity that, when clicked, uses a mediaplayer to start playing a sound file, and a notification is shown. I want the music service to be stopped and the notification removed when I click on the notification. I've been bashing my head against the wall for a few hours now as I'm unable to figure out what I'm doing wrong. Here is my service class:
public class MusicService extends Service {
public MusicService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.start();
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Hello")
.setTicker("Hello 2")
.setContentText("Hello 3")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(NOTIFICATION_ID.FOREGROUND_SERVICE, notification);
return START_STICKY;
}
public interface NOTIFICATION_ID {
public static int FOREGROUND_SERVICE = 101;
}
}