how to get notification in status bar at a particular time, i tried this, but every particular time the pendingIntents activity is bein called. I want the status bar's notification to be invoked. please help
public class MainActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Notification("abduct: ","kidnap");
}
#SuppressWarnings("deprecation")
private void Notification(String notificationTitle, String notificationMessage)
{
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(R.drawable.icon, "First word", 50000);
notification.setLatestEventInfo(MainActivity.this, notificationTitle, notificationMessage, null);
notificationManager.notify(1, notification);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 1*60*60 , pendingIntent ); //set repeating every 24 hours
}
}
The problem is with the PendingIntent you are providing the AlarmManager. By creating it with PendingIntent.getActivity() you're actually instructing it to start your activity when the specified time elapses.
What you need to do is:
Create a BroadcastReceiver and configure it in your AndroidManifest.xml file.
Instead of what you're currently doing, supply the AlarmManager with a PendingIntent to send a broadcast to this receiver (with PendingIntent.getBroadcast()).
In the receiver's onReceive(), build and show the notification.
You can find a clear and concise tutorial here.
Related
Not sending notification at selected time, when I ran my code, directly showed notification
and showed error as well
Here is the error message: E/NotificationManager: notifyAsUser: tag=null, id=12345, user=UserHandle{0}
I thought the error message was due to Build.VERSION.SDK_INT, but after adding that, the error message is still there.
Place all of these under onCreate:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE,9)
;
Intent intent = new Intent ();
intent.setAction("com.example.Broadcast");
PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0, intent,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, contentIntent);
and here is the extend.
public class wakeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
setNotification(context);
}
protected void setNotification(Context context){
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
String ChannelId = "12345";
int uniID = 12345;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,ChannelId )
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("Hi")
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentText("Please Rate.");
builder.setContentIntent(contentIntent);
//
// Send notification to your device
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.myApp");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"com.myApp",
"My App",
NotificationManager.IMPORTANCE_DEFAULT
);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
manager.notify(uniID, builder.build());
}
}
Can someone please help me with this?
You are very confused.
In your code you call NotificationManager.notify(). This will show the Notification immediately.
You do:
Intent intent = new Intent(this, MainActivity.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0, intent,0);
This won't work. You have created a PendingIntent which will be sent via broadcast using an Intent that is for an Activity! What do you want to happen? Do you want an Activity to be launched or do you want a BroadcastReceiver to be triggered?
I think what you want to do is as follows:
Create an Intent for a BroadcastReceiver, wrap that in a PendingIntent using getBroadcast() and pass that to the AlarmManager so that the broadcast Intent will be set at some future time.
Create a class that extends BroadcastReceiver. In onReceive() create the Notification and call NotificationManager.notify() to post the Notification. In the Notification you can set a PendingIntent that opens your Activity so that if the user clicks on the Notification your Activity will be launched. To do this, call PendingIntent.getActivity() and pass an Intent that contains MainActivity.class.
In my android application, I want to generate a notification when current time matches with the time that I have retrieved from my database. And the notification should be generated even if the application is not running. For this I have done something like this, but this is not working (no notification is being generated).
I am new to android, and I have seen many examples and tutorials for solving this issue, but they did not helped. So please give Answer that what should I do for getting the desired result?
In MainActivity.java I am doing this:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*here I am retrieving time from database*/
String time_from_database = "20:00:00";
if(Calendar.getInstance()==time_from_database) {
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, NotGen.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
alarmMgr.set(AlarmManager.RTC, Calendar.getInstance(), alarmIntent);
}
}
}
this is code of NotGen.java class:
public class NotGen extends BroadcastReceiver {
public NotificationCompat.Builder mBuilder;
#Override
public void onReceive(Context context, Intent intent) {
PendingIntent pIntent = PendingIntent.getActivity(context,0,intent,0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setTicker("Ticker Title");
mBuilder.setSmallIcon(R.drawable.my_img);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
mBuilder.setContentIntent(pIntent).getNotification();
mBuilder.setAutoCancel(true);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0,mBuilder.build());
}
}
Calendar.getInstance()==time_from_database will never work.
First, getInstance() is going to create a new instance, and == is object identity equality.
Second, time_from_database is a String ("20:00:00"). A Calendar instance will never equal that, if for no other reason than a Calendar is a combination of date and time.
You can achieved it using Service. Service will running in background all the time even your application is not running.
1) Create service and register it into Manifest file.
2) Start it on application start.
3) Into service you can generating your notification when current time will matched with database time.
For service example you can see below links
http://javatechig.com/android/android-service-example
http://www.tutorialspoint.com/android/android_services.htm
I found this example of an alarm notification and I would just like to ask you to change two things.
This is MainActivity:
public void setRepeatingAlarm() {
Intent intent = new Intent(this, MyAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(129600000), pendingIntent);
}
And this is MyAlarmService:
public class MyAlarmService extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Locali Torino";
CharSequence message = "Visita le serate!";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.disco,
"Visita le serate!", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}
}
In this way, when I launch my app, now I see the notification but I would like to see it do so only after "x" milliseconds.
And then I want to know how to launch the MainActivity clicking on the notification.
Thank you.
Call setRepeatingAlarm() with some delay. From service or from activity use e.g. Handler and post a runnable to it with small delay. If you are in activity, dont't forget to remove post action within your lifecycle methods, e.g. onStop(). If you want to make some action when user click on notification, edit contentIntent in your MyAlarmService.
E.g.
Intent action = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
action, 0);
Is there any way in Android to detect when a user swipes a notification to the left and deletes it? I'm using an alarmmanager to set a repeating alert and I need my repeating alert to stop when the notification is cancelled by the user. Here's my code:
Setting the repeating alert:
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), repeatFrequency, displayIntent);
My notification code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the notification ID.
int notifID = getIntent().getExtras().getInt("Reminder_Primary_Key");
//Get the name of the reminder.
String reminderName = getIntent().getExtras().getString("Reminder_Name");
//PendingIntent stores the Activity that should be launched when the user taps the notification.
Intent i = new Intent(this, ViewLocalRemindersDetail.class);
i.putExtra("NotifID", notifID);
i.putExtra("notification_tap", true);
//Add FLAG_ACTIVITY_NEW_TASK to stop the intent from being launched when the notification is triggered.
PendingIntent displayIntent = PendingIntent.getActivity(this, notifID, i, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.flag_red_large, reminderName, System.currentTimeMillis());
CharSequence from = "Here's your reminder:";
CharSequence message = reminderName;
notif.setLatestEventInfo(this, from, message, displayIntent);
//Pause for 100ms, vibrate for 250ms, pause for 100ms, and vibrate for 500ms.
notif.defaults |= Notification.DEFAULT_SOUND;
notif.vibrate = new long[] { 100, 250, 100, 500 };
nm.notify(notifID, notif);
//Destroy the activity/notification.
finish();
}
I know I need to call alarmManager.cancel(displayIntent) in order to cancel my repeating alarm. However, I don't understand where to put this code. I need to cancel the repeating alert ONLY when the user has tapped on the notification or dismissed it. Thanks for your help!
I believe that Notification.deleteIntent is what you are looking for. The doc says:
The intent to execute when the notification is explicitly dismissed by the user, either with the "Clear All" button or by swiping it away individually. This probably shouldn't be launching an activity since several of those will be sent at the same time.
To all those future people out there -- you can register a broadcast receiver to listen for notification delete inents.
Create a new broadcast receiver:
public class NotificationBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null || !action.equals(Config.NotificationDeleteAction)) {
return;
}
// Do some sweet stuff
int x = 1;
}
}
Register the broadcast receiver within your application class:
"If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that do not target your app specifically)."
Android Documentation.
registerReceiver(
new NotificationBroadcastReceiver(),
new IntentFilter(Config.NotificationDeleteAction)
);
You probably noticed the static variable Config.NotificationDeleteAction. This is a unique string identifier for your notification. It typically follows the following {namespace}{actionName} convention:
you.application.namespace.NOTIFICATION_DELETE
Set the delete intent on your notification builder:
notificationBuilder
...
.setDeleteIntent(createDeleteIntent())
...
Where, createDeleteIntent is the following method:
private PendingIntent createDeleteIntent() {
Intent intent = new Intent();
intent.setAction(Config.NotificationDeleteAction);
return PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_ONE_SHOT
);
}
Your registered broadcast receiver should receive the intent when your notification is dismissed.
You can also use an Activity PendingIntent, which may be simpler to implement if you have an Activity that can handle the dismissal, because you don't have to create and configure a broadcast receiver.
public static final String DELETE_TAG = "DELETE_TAG";
private PendingIntent createDeleteIntent(Context context) {
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra(DELETE_TAG, true);
return PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_ONE_SHOT
);
}
MyActivity would receive the intent in its onCreate(), and in this example, could look for the DELETE_TAG extra to recognize it.
i'm try to develop an app for organizing . so after setting an task for particular time, i created a notification, so this notification displays on the status bar and when the user touch on this, current activity will appear.
My problem is : when the notification appear, the activity is launched also.
there is anyways to prevent this ? i mean the activity don't start automatically when the notification appear, and the user have to click on the notification to wake the activity up.
I have class "Main" and an alarm manager inside. this alarm manager will fire at the particular time and start an another activity (DisplayNotification).
{
Intent intent = new Intent("com.test.DisplayNotification");
intent.putExtra("alarm_message", "Alarm");
intent.putExtra("item_name", "message");
PendingIntent broadcast = PendingIntent.getActivity(getBaseContext(), 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, mili, broadcast);
}
In the DisplayNotification class i have
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String message = getIntent().getExtras().getString("item_name");
Intent i = new Intent("com.test.Main");
PendingIntent detailsIntent =
PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.icon,
"Time's up!",
System.currentTimeMillis());
CharSequence from = "AlarmManager - Time's up!";
notif.setLatestEventInfo(this, from, message, detailsIntent);
nm.notify(1, notif);
//---destroy the activity---
finish();
}
Use a BroadcastReceiver to 'listen' for the result of the alarm and then have it create the Notification in its onReceive(...) method.