I'm trying to buld an alarm with notificatoin and rington.
- How should it be done properly?
What I do: From my activity i call the BroadcastReceiver by using alarmmanager, than in BroadcastReceiver I make the notification with NotificationCompat.Builder and after that I call the service.
- How to cancel the rington by swipeing out or double clicking the notification ?
{
private Intent notificationIntent;
@Override
public void onReceive(Context context, Intent intent) {
String title = intent.getStringExtra("myTitle");
notificationIntent = new Intent();
checkIntent(title, context);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.dumbbell)
.setContentTitle("Tracker")
.setContentText(title)
.setAutoCancel(true);
notificationManager.notify(1, builder.build());
Intent ringtoneIntent = new Intent(context, AlarmService.class);
context.startService(ringtoneIntent);
}
private void checkIntent(String title, Context context) {
switch (title){
case "Weight":
notificationIntent = new Intent(context, WeightActivity.class);
break;
case "Measure":
notificationIntent = new Intent(context, measurActivity.class);
break;
case "Pr":
notificationIntent = new Intent(context, PrsActivity.class);
break;
case "Macros":
notificationIntent = new Intent(context, DietActivity.class);
break;
}
}
public class AlarmService extends Service {
private MediaPlayer alarmSong;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarmSong = MediaPlayer.create(this, R.raw.willy_william_voodoo);
alarmSong.start();
System.out.println("RING RING");
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
System.out.println("removed");
}
}