Android notification not able to access the received string - java

I receive a notification in broadcast receiver like this in MainActivity.java. I need to access this string textMessage for my other classes -
if (intent.getAction().equals("NOTIFY_TEXT_MESSAGE")){
String textMessage = intent.getStringExtra("TextMessage");
Intent noti_intent = new Intent(MainActivity.this, NotificationReceiver.class);
noti_intent.setAction("NotificationReceived");
noti_intent.putExtra("NotificationMessage",textMessage);
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, noti_intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.text_messages)
.setContentTitle(getResources().getString(R.string.Message_Title))
.setContentText(textMessage)
.setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
.setPriority(NotificationCompat.PRIORITY_HIGH) //must give priority to High, Max which will considered as heads-up notification
.addAction(0,
getString(R.string.Open), pi)
.setAutoCancel(true);
builder.setSound(soundUri);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
In NotificationReceiver.class,
public class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("NotificationReceived".equals(action)) {
String msg = MainActivity.NotificationMessage;
Log.v("shuffTest","msg" + msg);
}
}
}
In my Manifest,
<receiver android:name="com.example.NotificationReceiver">
<intent-filter>
<action android:name="NotificationReceived" />
</intent-filter>
</receiver>
Why the log msg is not appearing. What is the mistake in my code?

Try to get the message from the intent, like this:
public class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("NotificationReceived".equals(action)) {
String msg = intent.getStringExtra("NotificationMessage");
Log.v("shuffTest","msg" + msg);
}
}
}

Related

Android studio notifications implemented but not showing

I have implemented android notifications in android studio. I was creating notification for a media player. following is the function for showing notifications
public void showNotification(int playPauseBtn)
{
Intent intent = new Intent(this, PlayerActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent prevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture = null;
try
{
picture = getAlbumArt(listSongs.get(position).getPath());
} catch (Exception ignored)
{
}
Bitmap thumb;
if (picture != null)
{
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
} else
{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.icon_music);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_1).setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setContentTitle(listSongs.get(position).getTitle())
.setContentText(listSongs.get(position).getArtist())
.addAction(R.drawable.ic_baseline_skip_previous_24, "Previous", prevPending)
.addAction(R.drawable.ic_baseline_skip_next_24, "Next", nextPending)
.addAction(playPauseBtn, "pause", pausePending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setContentIntent(contentIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
Toast.makeText(PlayerActivity.this, "Nitification created", Toast.LENGTH_SHORT).show();
}
In the function parameter (playPauseBtn) I am sending the play icon or the pause icon depending upon weather the song is playing or is paused.
Function call is made like following:
showNotification(R.drawable.ic_baseline_pause_24);
OR
showNotification(R.drawable.ic_baseline_play_arrow_24);
But when ever I call this function the notification doesn't show up. I am also using the notification channel but still it is not working. I have also tried to debug the code but the code runs fine, still the notification doesn't show up. please advise
try this.
put this code in your Activity/fragment;
public void getNotification(){
int notifId =new Random().nextInt(500); //get random id
NotificationManager notificationManager;
Notification notification;
notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelID = "1";
channelName = "news";
channelDesc = "news description";
NotificationChannel notificationChannel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription(channelDesc);
notificationChannel.enableLights(true);
notificationChannel.setSound(null, null);
notificationChannel.setLightColor(Color.GREEN);
notificationManager.createNotificationChannel(notificationChannel);
}
RingtoneManager.getRingtone(mContext,
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).play();
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title Of MUSIC")
.setContentText("Content")
.setVibrate(new long[]{100, 500, 500, 500, 500})
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
Intent actionReadMessage = new Intent(mContext, NotifAction.class);
actionReadMessage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
actionReadMessage.setAction("Play");
actionReadMessage.putExtra("NotifId",notifId);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(mContext, notifId, actionReadMessage,PendingIntent.FLAG_CANCEL_CURRENT);
Intent mainAction = new Intent(mContext, NotifAction.class);
mainAction.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAction.setAction("Pause");
mainAction.putExtra("NotifId",notifId);
PendingIntent PausePendingIntent = PendingIntent.getBroadcast(mContext, notifId, mainAction,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(PausePendingIntent);
builder.addAction(R.mipmap.ic_launcher, "Play", playPendingIntent);
builder.addAction(R.mipmap.ic_launcher, "Pause", PausePendingIntent);
notification = builder.build();
notificationManager.notify(notifId, notification);
}
and create class NotifAction.class for handle all action:
public class NotifAction extends BroadcastReceiver {
private static final String TAG = "maybe";
private MediaPlayer mp;
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Bundle extra = intent.getExtras();
if (extra != null) {
int notifId = extra.getInt("NotifId");
if (action.equals("Play")) {
mp = MediaPlayer.create(context, R.raw.music);
handleMusicState(mp);
} else if (action.equals("Pause")) {
handleMusicState(mp);
setMessageRead(notifId, context);
} else {
Toast.makeText(context, "extra action !", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Empty extra !", Toast.LENGTH_SHORT).show();
}
}
private void setMessageRead(int id, Context context) {
// other method
clearNotification(id, context);
}
private void clearNotification(int id, Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
private void handleMusicState(MediaPlayer mediaPlayer) {
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
else mediaPlayer.start();
}
}
define this receiver to manifest:
note:in tag
<receiver android:name=".NotifAction">
<intent-filter>
<action android:name="Play" />
<action android:name="Pause" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
FIX
Donot use .setMediaSession(mediaSessionCompat.getSessionToken()) in .setStyle() in the code given in the question
simply just use
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle())

Android Repeated Notifications not working When App is Closed

I want to send notification everyday on a particular time. The code is working when the app is opened. But when it closed and remove, the notifications are not showing. I have used broadcast receiver and service to this. The code is given below. Can anyone help to clear this issue.
Manifest File
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" />
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
intent = new Intent(context, MyService.class);
context.startService(intent);
}}
MyService.java
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotification();
return Service.START_STICKY;
}
private static final String NOTIFICATION_CHANNEL_ID = "Channel01";
private void createNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = preferences.getString("name", "User");
name = name.split(" ")[0];
String namee = "Remainder";
String description = "Remainder to update Wallet";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, namee, importance);
notificationChannel.setDescription(description);
Intent notifyIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, notifyIntent, 0);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("Remainder")
.setContentText("Hey " + name + ", Let's update your wallet")
.setSmallIcon(R.drawable.wallet)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.wallet_new))
.setContentIntent(pendingIntent)
.build();
NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
// Issue the notification.
notificationManager.notify(1 , notification);
}
}}
Activity.java
Intent notifyIntent = new Intent(getApplicationContext(), MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, notifyIntent, 0);
alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeMilli, timeInterval, pendingIntent);
You shouldn't use any part of application to do that. Services, JobScheduler, or Work Manager sooner or later will be killed by the system to prevent battery drain.
In my opinion the best way to send repeated notifications is to use firebase cloud messaging triggered with external cron job (e.g. php on firebase functions).
Also make sure to deliver the notification to the system tray not to the application. To do that use FCM DataMessages. Data messages are delivered to system tray and are always display - even if service is not running.

Unique Notifications at Unique Times with broadcastReceiver

i am currently devoloping small app and i struggle about sending notifications.
My Goal: I have different tasks and they need to send unique notifications at unique time to user even
while app is closed.
What I did?: I did create different broadCastReceiver's to make them work in harmony with
alarmManager' s but even i changed the request code , flag or channel code, i do get notifications at
same time if user enables notifications for more than one task, but alarmManagers for notifications
are not supposed to work after same time.
'receiver' part of AndroidManifest.xml
<receiver
android:name=".BroadcastReceiver"
android:exported="true">
<intent-filter>
<action
android:name="pendingIntent">
</action>
</intent-filter>
</receiver>
<receiver
android:name=".BroadcastReceiver2"
android:exported="true">
<intent-filter>
<action
android:name="pendingIntent2">
</action>
</intent-filter>
</receiver>
first and second broadCastReceiver
public class BroadcastReceiver extends android.content.BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "100")
.setSmallIcon(R.drawable.logologo)
.setContentTitle("Title")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(100, builder.build());
}
}
}
public class BroadcastReceiver2 extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"102")
.setSmallIcon(R.drawable.logologo)
.setContentTitle("Title")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(102, builder.build());
}
}
First and second Channel
public void createChannel1()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
CharSequence name = "channel1";
String description = "channel1 description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel1 = new NotificationChannel("100", name, importance);
channel1.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel1);
}
}
public void createChannel2()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
CharSequence name = "channel2";
String description = "channel2 description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel2 = new NotificationChannel("102", name,importance);
channel2.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel2);
}
}
Activity that needed to send Notification from first broadCastReceiver on Channel1 and
Activity that needed to send Notification from second broadCastReceiver on Channel2
button30.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(SmokeActivity.this, BroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(SmokeActivity.this, 100, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60, pendingIntent);
}
});
button29.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(WaterActivity.this, "Notifications Set", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(WaterActivity.this, BroadcastReceiver2.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(WaterActivity.this,0,intent2,0);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
// Set the alarm to start at 8:30 a.m.
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(System.currentTimeMillis());
calendar2.set(Calendar.HOUR_OF_DAY, 8);
calendar2.set(Calendar.MINUTE, 30);
alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(),
1000*45, pendingIntent2);
}
});
For anyone suffering from same problem, the thing is android system does not allow us to send notification after first 10 minute when you create notification.

How to send notification on boot completed?

I've got the following class called AlarmNotificationReceiver.
The idea is to send a notification when the device is turned out. Something seems to be wrong since this isn't happening. Any ideas why?
public class AlarmNotificationReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle("HEY I WAS INITIALIZED!");
builder.setContentText("Good luck");
builder.setSmallIcon(R.drawable.alert_icon);
builder.setAutoCancel(true);
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.notif_red));
//notification manager
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
manager.notify(1234, notification);
}
}
}
I also added the following lines to the manifest:
<receiver android:name=".AlarmNotificationReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
You are missing creation of notification channel. You can create notification as follows:
public class AlarmNotificationReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
...
createNotificationChannel(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,1000);
...
}
}
private void createNotificationChannel(final Context context) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "ChannelName";
String description = "Channel description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(1000, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}

Repeating notification sound

Is it possible (and if yes how) to make push notification sound repeat until it's read? I am creating app that notifies user about new event in app, but user needs to read notification as soon as possible. When user "reads" notification it should stop ringing. Here's code:
public class GCMIntentService extends IntentService {
String mes;
HelperGlobals glob;
public GCMIntentService() {
super("GcmIntentService");
}
#SuppressLint("SimpleDateFormat")
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
glob = (HelperGlobals) getApplicationContext();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
// .... Doing work here
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
public void createPush(String title, String msg, Intent intent) {
Uri soundUri = Uri.parse("android.resource://example.project.com/" + R.raw.notification);
Context context = getApplicationContext();
Intent notificationIntent = new Intent(context, DoNothing.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification n = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
n.defaults |= Notification.DEFAULT_VIBRATE;
//n.defaults |= Notification.DEFAULT_SOUND;
n.sound = soundUri;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
And BroadcastReceiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BukuLog", "Receiver");
// Explicitly specify that GcmMessageHandler will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
like this:
Notification note = mBuilder.build();
//here
note.flags = Notification.FLAG_INSISTENT;
mNotificationManager.notify(1, note);
int FLAG_INSISTENT : Bit to be bitwise-ored into the flags field that if set, the audio will be repeated until the notification is cancelled or the notification window is opened.
follow android developer

Categories

Resources