Just display notification without start the activity - android

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.

Related

Want to write a code to only send notification at certain time, but somehow the alarmManager is not working and it shows some errors

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.

I want the status bar's notification to be invoked

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.

Alarm and notification

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);

How to detect if a notification has been dismissed?

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.

Android reminder!

I would like to ask which service and how to use to make reminder in android... Let's say: after 10 minutes from now show me notification in notification bar...
Thanks for your answer
Obviously you should use AlarmManager in order to setup something to be executed in given PERIOD.
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), PERIOD, pi);
where the PERIOD is your time to something that should be executed in OnAlarmReceiver.
And then, just implement method in
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager nm = (NotificationManager);
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.tickerText = "10 Minutes past";
nm.notify(0, notification);
}
Enjoy.
You should use AlarmManager. With it you can schedule an intent to be delivered. Create a BroadcastReceiver to get it and show the notification.
Somethink like this i guess, you start an runnable after 10min and open an notification in the runnable's code.
Runnable reminder = new Runnable()
{
public void run()
{
int NOTIFICATION_ID = 1324;
NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.icon, "message", System.currentTimeMillis());
// Add and AUTO_CANCEL flag to the notification,
// this automatically removes the notification when the user presses it
note.flags |= Notification.FLAG_AUTO_CANCEL;
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this, ActivityToOpen.class), 0);
note.setLatestEventInfo(this, "message", title, i);
notifManager.notify(NOTIFICATION_ID, note);
}
};
Handler handler = new Handler();
handler.postDelayed(reminder, 600000);

Categories

Resources