addAction listener on notification with service - java

I've created a media player service for playing streamed audio file, i've added a notification with an action to pause. I would like to know how to get the action listener of this action in my service.
MediaPlayerService.java
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(this, MainActivity.class), 0);
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
noti = new Notification.Builder(getApplicationContext())
.setOngoing(true)
.setContentTitle("Lecture")
.setTicker("Lecture d'un message en cours")
.setContentText("Message audio en cours")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.addAction(android.R.drawable.ic_media_pause, "Pause", pendingIntent);
notificationManager.notify(0, noti.build());
return START_STICKY;
}

i am sure this question may have been resolved but I had the same issue and was able to resolve it by adding a different pending intent for every action. This is shown in the code below:
private static Notification buildNotification(Context context, String filename, int recordFlag,boolean stopFlag,boolean playFlag) {
PendingIntent pIntent = createPendingIntent(REQUEST_CODE_ACTIVIY, context, false);
PendingIntent delIntent = getDeleteIntent(context);
// Build notification
// Actions are just fake
int drawRecord =R.drawable.ic_record_audio;
Notification.Builder builder = new Notification.Builder(context.getApplicationContext())
.setContentTitle(RECORD_AUDIO)
.setContentText(filename).setSmallIcon(R.drawable.ic_audio_list)
.setContentIntent(pIntent)
.setDeleteIntent(delIntent);
builder = builder.addAction(drawRecord, RECORD, createPendingIntent(REQUEST_CODE_SERVICE_RECORD, context, true));
builder = builder.addAction(R.drawable.ic_stop_white, STOP, createPendingIntent(REQUEST_CODE_SERVICE_STOP, context, true));
builder = builder.addAction(R.drawable.ic_play_white, PLAY, createPendingIntent(REQUEST_CODE_SERVICE_PLAY, context, true));
return builder.build();
}
Hope this helps

Related

Updating notifications after being added

I want to update the content for a reminder after it has been added before being received by the user. After setting a reminder through AlarmManager using the data stored in sqlite database, the notification from the reminder set only shows the data, title and description, that was first added, not any updated data stored corresponding to the ID as primary key.
Things I have tried:
cancelling the pending intent for the reminder then setting it again after updating the data stored in the database but it still displays the same result.
using an activity for adding data to be stored in the database to set a reminder and using another activity for updating this data as an attempt to update the reminder content with the same ID issued. One result shows two notifications received, one with initial title and description, and the other with updated information.
Currently, the methods I use to set and cancel a reminder is in my Adapter class for Recyclerview. I am stuck on updating although adding and cancel works fine.
Update: Now I use two separate activities for the add and update reminder functions.
For adding a reminder:
databaseManager.addReminder(titlePicked, descriptionPicked, timePicked, datePicked, dateTimePicked);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
setAlarm();
private void setAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class);
intent.putExtra("DateTime", dateTimePicked);
intent.putExtra("NotifID", remId);
intent.putExtra("Title", titlePicked);
intent.putExtra("Description", descriptionPicked);
PendingIntent addIntent = PendingIntent.getBroadcast(this, remId, intent, 0);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Date.parse(dateTimePicked), addIntent);
}
For updating a reminder:
databaseManager.updateReminder(remindId, titlePicked2, descriptionPicked2, timePicked, datePicked, dateTimePicked);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
updateAlarm();
private void updateAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class);
intent.putExtra("DateTime", dateTimePicked);
intent.putExtra("NotifID", remindId);
intent.putExtra("Title", titlePicked2);
intent.putExtra("Description", descriptionPicked2);
PendingIntent updateIntent = PendingIntent.getBroadcast(this, remindId, intent, 0);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Date.parse(dateTimePicked), updateIntent);
}
Receiver class:
public class ReminderReceiver extends BroadcastReceiver {
private static final String CHANNEL_ID = "CHANNEL_REMIND";
String DateTimeChoice, TitleChoice, DescriptionChoice;
int notificationID;
#Override
public void onReceive(Context context, Intent intent) {
DateTimeChoice = intent.getStringExtra("DateTime");
notificationID = intent.getIntExtra("NotifID", 0);
TitleChoice = intent.getStringExtra("Title");
DescriptionChoice = intent.getStringExtra("Description");
Intent mainIntent = new Intent(context, ViewReminder.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, notificationID, mainIntent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// For API 26 and above
CharSequence channelName = "My Notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(TitleChoice)
.setContentText(DescriptionChoice)
.setContentIntent(contentIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(context.getResources().getColor(R.color.purple_700))
.setAutoCancel(true);
notificationManager.notify(notificationID, builder.build());
}
Adapter class:
int remindId = reminder.getReminderId();
databaseManager = new DatabaseManager(holder.view.getContext());
sqLiteDB = databaseManager.getWritableDatabase();
public void onClick(View view) {
Reminder reminder = remindList.get(holder.getAdapterPosition());
PopupMenu popupMenu = new PopupMenu(view.getContext(), view);
popupMenu.setGravity(Gravity.END);
popupMenu.getMenu().add("Edit").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Intent intent = new Intent(view.getContext(), UpdateReminderActivity.class);
intent.putExtra("reminderId", remindId);
intent.putExtra("title", reminder.getReminderTitle());
intent.putExtra("definition", reminder.getReminderDefinition());
view.getContext().startActivity(intent);
return true;
}
});
For updating a pending intent, you need to use FlAG_UPDATE_CURRENT with the same id you used earlier to set the initial intent.
If you want to update the alarm associated with that pending intent, you need to cancel the old alarm & then the old PendingIntent. Then create a new PendingIntent like this,
PendingIntent updateIntent = PendingIntent.getBroadcast(this, remindId, intent,PendingIntent.FLAG_UPDATE_CURRENT);
and set it to the alarm.

Clear app notifications in android studio

I have an application that sends notifications, but when the user leaves the application the notification is still there, in case he does not click on it.
So, when the user logs out, or the session user is "null", the notifications will be automatically deleted.
My code:
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void enviarNotificacao(){
Intent intent = new Intent(this, BottomNavigation.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.putExtra("totens", listaTotem);
int id = (int) (Math.random()*1000);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("Olá Marujo!!!");
builder.setContentTitle("Capitão Cupom");
builder.setContentText("Um novo tesouro próximo de você");
builder.setSmallIcon(R.drawable.logo);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
builder.setContentIntent(pi);
builder.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(id, builder.build());
Notification n = builder.build();
n.vibrate = new long[]{150, 300, 150, 600};
notificationManager.notify(R.drawable.logo, n);
try {
Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone toque = RingtoneManager.getRingtone(this, som);
toque.play();
}catch (Exception e){
}
Sessao.instance.setSailor(sailor);
}
NotificantionManager.cancel(id) cancels a notification with that id. NoticiationManager.cancelAll() cancels all notifications from this app. Detecting when a session ends will obviously be business logic you need to build. When it happens, call one of the 2 above functions.
Override onPause() in Activity and put this inside:
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
When leaves the application call it
notificationManager.cancel(NOTIFICATION_ID);

How to create notification

I want to create a simple notification in my app, but I can't. I searched for that, I read questions here and the google doc, but I don't know why it is not working. I watched that code from a video, but it doesnt work too.
private final String CHANNEL_ID = "personal_notifications";
private final int NOTIFICATION_ID = 001;
public void displayNotification(View view) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,CHANNEL_ID);
builder.setSmallIcon(R.drawable.power);
builder.setContentTitle("Noti");
builder.setContentText("mukodj mar");
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
I use this code in a BroadcastReceiver:
public class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, MainActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
StringBuilder sb = new StringBuilder();
NotificationCompat.BigTextStyle contentStyle = new NotificationCompat.BigTextStyle();
contentStyle.bigText((CharSequence) sb.toString());
NotificationCompat.Builder builder = new NotificationCompat.Builder(context) // channel ID missing
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.icon)
.setStyle(contentStyle)
.setContentTitle("Title")
.setContentText(sb.toString())
.setAutoCancel(true);
notificationManager.notify(100, builder.build());
}
I think you forgot the last line:
notificationManager.notify(100, builder.build());
I got it. I made notification channel and its working now, anyway thanks guys!

Alarm Doesn't work when app is closed

Basically, I am trying to build an alarm app which has some buttons with some predefined Date and Time. I have tried using AlarmManager and broadcast receiver in the first place but didn't work. So, I used foreground service with alarmManager but still, the alarm doesn't fire when the app is destroyed. I am a newbie. I tried searching the internet but I had no luck. Hope there is a lot of people here to help me out. Thanks in Advance.
Here I am just trying to set only one alarm for testing. Otherwise, I am using a variable as request code for multiple alarms.
AndroidManifest.xml
<receiver android:name=".AlarmReceiver" />
<activity
android:name=".Activity.PlayerDetailsActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity android:name=".Activity.FixtureActivity" />
<service android:name=".MyService"/>
MyService.java
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
Log.e("service","service");
long longExtra = intent.getLongExtra(Constants.ALARM_TIME, 0000);
//Testing Area Start
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(longExtra);
int mMin = calendar.get(Calendar.MINUTE);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR_OF_DAY);
Log.e("hour min month day"," "+mHour + " : "+mMin+" month : "+mMonth+" "+" Date : "+mDay+" ");
String currentDateTime=getDeviceDateTime();
Log.e("CurrentdateTime",""+currentDateTime);
Log.e("longExtra",""+longExtra);
//Testing Area End
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("dfdf")
.setSmallIcon(R.drawable.ic_notifications_black_24dp)
.setContentText("dfdfd").build();
startForeground(3, notification);
}
/*Intent alertIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Log.d("I",""+longExtra);
alarmManager.set(AlarmManager.RTC_WAKEUP, 6000000, PendingIntent.getBroadcast(getApplicationContext(), 0, alertIntent,
PendingIntent.FLAG_ONE_SHOT));*/
AlarmManager manager= (AlarmManager)getSystemService(ALARM_SERVICE);
Intent myIntent;
myIntent = new Intent(getApplicationContext(),AlarmReceiver.class);
myIntent.putExtra("check",true);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
Long finalTime =longExtra-System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
manager.setExact(AlarmManager.RTC_WAKEUP,longExtra,pendingIntent);
}
else
manager.set(AlarmManager.RTC_WAKEUP,longExtra,pendingIntent);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Alarmreceiver.java
public class AlarmReceiver extends BroadcastReceiver
{
public static final String CHANNEL_ID = "47";
#Override
public void onReceive(Context context, Intent intent)
{
intent = new Intent(context, SplashActivity.class);
intent.putExtra("not",true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(context,CHANNEL_ID);
notificationCompat.setSmallIcon(R.drawable.ic_notifications_black_24dp);
notificationCompat.setContentTitle("My Noticiation");
notificationCompat.setContentText(getPreferences(context).getDateTime());
notificationCompat.setContentIntent(pendingIntent);
notificationCompat.setSound(alarmSound);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel name", importance);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Notification notification = notificationCompat.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(100,notification);
Toast.makeText(context, "Alarm Working", Toast.LENGTH_SHORT).show();
}
}
you have to start your service so then it can set alarm and fire reciever
start it like this from your activity class
Intent intent=new Intent(this,MyService.class);
startService(intent);
Consider using JobScheduler as a persistence mechanism. It is wakeful and handles the wake locks for you. Only downside it's for Android SDK >= 21 (Lollipop).
There's also a new friend in town that does the backward compatibility for you: WorkManager and will work with all version of Android, even below Lollipop.
Intent myIntent;
myIntent = new Intent(this, AlarmReceiver.class);
myIntent.putExtra("check",true);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
=============================
Would you change your above code like this ?
Intent myIntent;
myIntent = new Intent(this , MyService.class);
myIntent.setAction("REQUEST_FROM_ALARM_MANAGER");
PendingIntent pendingIntent = PendingIntent.getForegroundService(this,0,myIntent,0);
====================================================
And Service class
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = this;
Log.e(TAG, "onStartCommand " + intent);
if(intent == null) {
return START_NOT_STICKY;
}
if("REQUEST_FROM_ALARM_MANAGER".equals(intent.getAction())){
// show Notification here for your foreground service
}
return START_NOT_STICKY;
}
You have to start a service that survive to your app, you can see here how to do it

Stop service with PendingIntent

I have an Ongoing notification on my radio app and I already managed to start my main activity from the notification but now I'm trying to add a button to the notification to stop the streaming service.
This is my notifaction method inside the service:
#SuppressWarnings("deprecation")
private void createNotification() {
int myIconId = R.drawable.ic_pause;
Intent mIntent = new Intent(context, StreamingService.class);
Notification notification;
Bundle bundle = new Bundle();
bundle.putInt("list", list);
PendingIntent stopIntent = PendingIntent.getService(context, 0, mIntent, 0) ;
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
0, new Intent(getApplicationContext(), MainActivity.class)
.putExtras(bundle), PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification();
notification.tickerText = station.getRadioName();
notification.icon = R.mipmap.ic_launcher;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(getApplicationContext(),
station.getRadioName(), null, pi);
} else {
notification = new NotificationCompat.Builder(context)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(station.getRadioName())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(
BitmapFactory.decodeResource(
context.getResources(),
R.mipmap.ic_launcher))
.addAction(myIconId,"STOP", stopIntent)
.setOngoing(true).setContentIntent(pi).build();
}
startForeground(NOTIFICATION_ID, notification);
}
This is my OnStartCommand:
public int onStartCommand(Intent intent, int flags, int startId) {
task = new ProgressTask();
task.execute();
return START_NOT_STICKY;
}
I did the Intent and the PendingIntent to start the service, but how can I set the service to stopSelf() using a PendingIntent?
I'm stuck at this for days, thanks in advance for the help.
in your OnStartCommand use this
if(intent.getAction().equals("STOP"))
stopSelf();
JRowan put me in the right direction, thanks man.
I added this line to my notification method:
mIntent.setAction("STOPME");
And this is my onStartCommand now:
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent.getAction()!=null && intent.getAction().equals("STOPME")){
stopSelf();
return START_NOT_STICKY;
}
else {
task = new ProgressTask();
task.execute();
return START_NOT_STICKY;
}
}

Categories

Resources