I have the following code:
public void sendNotification() {
try {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
final Intent intent = new Intent(this, NotifyBroadcastReceiver.class);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
builder.setContentTitle("Notifications Title");
builder.setContentText("Your notification content here.");
builder.setSubText("Tap to view the website.");
builder.setAutoCancel(true);
final Intent noted = new Intent(this, NotifyBroadcastReceiver.class);
noted.setAction("com.mawaeed.common.LaunchActivity");
PendingIntent notedpendingIntent = PendingIntent.getBroadcast(this, 0, noted, 0);// PendingIntent.FLAG_UPDATE_CURRENT ) ;
builder.addAction(0, "Noted", notedpendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}catch(Exception exo) {
Toast.makeText(this, exo.toString(),Toast.LENGTH_LONG).show();
}
}
Also I have my BroadcastReceiver
public class NotifyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"ddd",Toast.LENGTH_LONG).show();
Toast.makeText(context,"app",Toast.LENGTH_LONG).show();
}}
I am calling sendNotification from FirebaseMessagingService, Notification appears normally.
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification();
}
When clicking on the notification or Noted action, BroadcastReceiver onReceive not calling,
I already registered my BroadcastReceiver in mainafist
<receiver android:name=".NotifyBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>
</receiver>
The strange thing is I created a new application and copied all the code above to it, and I called the sendNotification from onCreate(), and when clicking on the notification it calls onReceive without problem.
I also tried same with my Application and called sendNotification from onCreate of my main activity, Notification appears but clicking on notification or Noted action not calling onReceive
Why it is not working from my application
I had to uninstall the app first then install it again, and now it works.
Related
My app simply receives a broadcast from another app. I am new to broadcast receiver so I am facing problems.
I want that when my app receive a broadcast message then in the notification panel a notification appears.
I tried a lot but find nothing on the internet.
I tried youtube videos and StackOverflow but I found nothing.
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "EBR triggered", Toast.LENGTH_LONG).show();
// The following code doesn't work. I copy this from StackOverflow//
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(context);
builder.setAutoCancel(false);
builder.setTicker("Ticker text");
builder.setContentTitle("Content of Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext...");
builder.setNumber(100);
builder.build();
// add as notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
No errors and I was expected that there will be a notification icon appears when broadcast receives but nothing happened.
Here is a simple example of broadcast receiving.
App 1 (sender)
Intent intent = new Intent("MY_NOTIFICATION");
intent.setComponent(
new ComponentName("com.example.stackoverflow", "com.example.stackoverflow.MyReceiver")
);
intent.putExtra("data","Notice me senpai!");
sendBroadcast(intent);
App 2 (receiver)
AndroidManifest.xml:
...
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="MY_NOTIFICATION"/>
</intent-filter>
</receiver>
MyReceiver.java:
public void onReceive(Context context, Intent intent) {
String data = intent.getStringExtra("data");
Toast.makeText(context, data, Toast.LENGTH_LONG).show();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
NotificationChannel channel = new NotificationChannel("CHANNEL_ID", "name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("description");
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "CHANNEL_ID")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("textTitle")
.setContentText(data)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
notificationManager.notify(1, builder.build());
}
Please note that there are Broacast limitations since Android 8. So you need to to provide the explicit class for handling i.e setComponent param along with action
i m creating custoom notification in my app.the notification shows up,but when i click on button,the button doesnt work.i dont know what to do.i looked in all the answer on stackoverflow but didnt get the idea.so,please help me.
this is code for notification
private void customNotification() {
Intent closeButton = new Intent("Download_Cancelled");
closeButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(getContext(), 0, closeButton, 0);
RemoteViews notificationView = new RemoteViews(getContext().getPackageName(), R.layout.notification);
NotificationManager notificationManager = (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext())
.setSmallIcon(R.drawable.music)
.setContent(notificationView)
.setChannelId(ID);
notificationView.setOnClickPendingIntent(R.id.next, pendingSwitchIntent);
notificationManager.notify(0, builder.build());
}
this is broadcast activity
public class NotificationBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"thanks",Toast.LENGTH_LONG).show();
}
}
this is manifest
<receiver android:name=".BlankFragment2$NotificationBroadcast">
<intent-filter>
<action android:name="Download_Cancelled" />
</intent-filter>
</receiver>
I've successfully created a status bar notification but I want it to pop up 6 hours after the user exits the app.
I have the following code:
public class myClass extends superClass implements myinterface {
final int NOTIF_ID = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {.........}
/* more methods etc */ ......
#Override
protected void onDestroy() {
View iop = (View) findViewById(R.id.app);
sendNotification(iop);
super.onDestroy();
}
public void sendNotification(View view) {
// Use NotificationCompat.Builder to set up our notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//icon appears in device notification bar and right hand corner of notification
builder.setSmallIcon(R.drawable.ic_launcher);
// This intent is fired when notification is clicked
Intent intent = new Intent(view.getContext(), AndroidLauncher.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Large icon appears on the left of the notification
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Notifications Title");
// Content text, which appears in smaller text below the title
builder.setContentText("Your notification content here.");
// The subtext, which appears under the text on newer devices.
// This will show-up in the devices with Android 4.2 and above only
builder.setSubText("Tap to view documentation about notifications.");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(NOTIF_ID, builder.build());
}
A status bar notification pops up when the app is exited but I want it to popup after 6 hours since the time user exits the app. How do I go about it?
Thanks in advance!
You can use an AlarmManager to schedule a broadcast that contains your notification.
private void scheduleNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Scheduled Notification");
builder.setContentText(content);
builder.setSmallIcon(R.drawable.ic_launcher);]
Notification notification = builder.build();
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long futureInMillis = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(6);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Then use a BroadcastReceiver to receive the intent and show the notification.
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
Don't forget to register the receiver in your AndroidManifest.xml file.
(Source: https://gist.github.com/BrandonSmith/6679223)
create a new class which will execute the alarm using pending intent and alarm manager.
long time= 6*60*60*1000; //6 hours
new Alarm_task(this, time).run();
public class Alarm_task implements Runnable{
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;
long alarm_time;
public Alarm_task(Context context, long time) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.alarm_time = time;
}
#Override
public void run() {
// Request to start are service when the alarm date is upon us
//pop up a notification into the system bar not a full activity
Intent i = new Intent("intent name");
// can create a dialog in that intent or just call the sendNotification() function
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
/** Setting an alarm, which invokes the operation at alart_time */
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + alarm_time, operation);
}
}
define intent in your manifest file:
<activity
android:name=".Activity name"
android:label="#string/app_name" >
<intent-filter>
<action android:name="Intent name" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
now in that activity you can call Sendnotification() function during onCreate().. or show some UI according to your application
call this method from onDestroy
public void Remind (String title, String message)
{
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent .PutExtra ("message", message);
notificationIntent .PutExtra ("title", title);
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(context, 0 , notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
if (android.os.Build.VERSION.SDK_INT>16)
{
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+ 6*60*60*1000, broadcast);
}else
{
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 6*60*60*1000, broadcast);
}
}
Create a new JAVA file
public class Broadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent1) {
String message = intent1.getStringExtra ("message");
String title = intent1.getStringExtra ("title");
// This intent is fired when notification is clicked
Intent notificationIntent = new Intent(context, AndroidLauncher.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(AndroidLauncher.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Use NotificationCompat.Builder to set up our notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//icon appears in device notification bar and right hand corner of notification
builder.setSmallIcon(R.mipmap.ic_launcher);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Notifications Title");
// Content text, which appears in smaller text below the title
builder.setContentText("Your notification content here.");
// The subtext, which appears under the text on newer devices.
// This will show-up in the devices with Android 4.2 and above only
builder.setSubText("Tap to view documentation about notifications.");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(0, builder.build());
}
Register this Receiver in Manifest
<receiver android:name=".Broadcast">
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
You can do it by using alarm manager service and notification manager.
I'm trying to create notifications for my app that sends notifications when a certain task is due. Each task has a deadline time so I want to send a notification for each task when their deadline has passed.
My main class is called RecyclerViewDemoActivity and inside the onCreate() I have this:
public void setNotification()
{
Intent intent=new Intent(this,NotificationClass.class);
AlarmManager manager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
PendingIntent pendingIntent= PendingIntent.getService(this, 0, intent, 0);
// hardcoding the time just for this example
manager.set(AlarmManager.RTC_WAKEUP,1449208683000,pendingIntent);
}
and I have a NotificationClass that looks like this:
public class NotificationClass extends Service {
#Override
public void onCreate()
{
Intent resultIntent=new Intent(this, RecyclerViewDemoActivity.class);
PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
Notification nBuilder= new Notification.Builder(this)
.setContentTitle("This task is due!")
.setContentIntent(pIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1,nBuilder);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.grokkingandroid.samplesapp.samples.recyclerviewdemo" >
<uses-permission android:name="android.permission.READ_CALENDAR"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>
<application
android:name="com.teamvallartas.autodue.RecyclerViewDemoApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.teamv.RecyclerViewDemoActivity"
android:label="#string/app_name"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I looked at this resource for the code above and also Vogella's resource on notifications but I don't know why this is not working.
Check if onCreate of Service class is getting called. If it is, then the problem is "You placed your code at wrong method.".
You need to move code into onStartCommand(Intent intent, int flags, int startId).
Like
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent resultIntent=new Intent(this, RecyclerViewDemoActivity.class);
PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
Notification nBuilder= new Notification.Builder(this)
.setContentTitle("This task is due!")
.setContentIntent(pIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1,nBuilder);
// If we get killed, after returning from here, restart
return START_STICKY;
}
Update your manifest and add this entry to it
<service android:name=".NotificationClass" />
you can do it in this way ,
1st > create one local broadcast receiver ,
inside onReceive() method , put your code stuff for generate notification
,that is your setNotification() method .
2nd > you just register that broadcast receiver inside onCreate() and unregister it inside onPause() or onDestory() method . like this ...
ReceiverActivity.java
public void onCreate(Bundle savedInstanceState) {
...
// Register your broadcast receiver here ...
// with actions named "custom-event-name"...
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
protected void onDestroy() {
// Unregister your receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
//here comes our receiver ...
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//called setNotification() here ...
}
};
Now let suppose you want to generate notification on click event of your button then fire intent like this,
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "Its me!!!!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
your **setNotification()**should be like this ..
public void Notification(Context context, String message) {
// Set Notification Title
String strtitle = context.getString(R.string.notificationtitle);
// Open NotificationView Class on Notification Click
Intent intent = new Intent(context, NotificationView.class);
// Send data to NotificationView Class
intent.putExtra("title", strtitle);
intent.putExtra("text", message);
// Open NotificationView.java Activity
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create Notification using NotificationCompat.Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context)
// Set Icon
.setSmallIcon(R.drawable.logosmall)
// Set Ticker Message
.setTicker(message)
// Set Title
.setContentTitle(context.getString(R.string.notificationtitle))
// Set Text
.setContentText(message)
// Add an Action Button below Notification
.addAction(R.drawable.ic_launcher, "Action Button", pIntent)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Dismiss Notification
.setAutoCancel(true);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
i am trying to fire notification in at a particular time using AlarmManager and Notification manager. i am facing a strange problem. when notification is fired only sound plays but notification is not shown in the notification drawer.
i got an error in the log
04-26 11:32:09.217 1222-1222/? E/NotificationService﹕ WARNING: In a future release this will crash the app: com.example.shiv.selftweak
my code is .
The class which calls the AlarmManager
Intent intent1 = new Intent(this, FireNotification.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 1000, intent1, 0);
AlarmManager am = (AlarmManager)this.getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), pendingIntent);
FireNotification class
public class FireNotification extends Service {
#Override
public void onCreate() {
Intent intent = new Intent(this, MainActivity.class);
long[] pattern = {0, 300, 0};
PendingIntent pi = PendingIntent.getActivity(this, 1234, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Self tweak")
.setContentText("Habbits are waiting for last dones")
.setVibrate(pattern)
.setAutoCancel(false);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(false);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(1234, mBuilder.build());
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Android Menifest
<service android:name=".FireNotification"></service>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
when notification fires only sound plays. but it is not getting shown in the notification drawer which shows no notification.
The problem is that you haven't specified mBuilder.setSmallIcon(R.drawable.ic_launcher).
Basically you have to set smallIcon, contentTitle and contentText. If you miss any of those the Notification will not be displayed at all! That's clearly specified HERE (also you can read more about notifications there as well).