I have a foreground service, and I'd like to make the Notification open the MainActivity when the user clicks on the Notification.
The method for creating the Notification in the custom Service class is:
public void setForeground(final int notificationID, final int notificationIconID,
final String notificationTickerText,
final String notificationTitle, final String notificationText){
Notification notification = new Notification(notificationIconID, notificationTickerText,
System.currentTimeMillis());
notification.setLatestEventInfo(this, notificationTitle,
notificationText, PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()), 0));
startForeground(notificationID, notification);
}
How do I modify it to include the open (if the MainActivity is currently open) or start MainActivity on Notification click functionality?
If you want to open any Activity by clicking notification, then you need to implement TaskStackBuilder
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Related
I want to send notification by BroadcastReceiver. Notification sent by AlarmReceiver but again sent notification when i clicked the notification. The same thing happens again, again and again like endless loop
Here is my AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher);
// This intent is fired when notification is clicked
Intent i = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
// Notifcation notify sound
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// 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(context.getResources(), R.mipmap.ic_launcher));
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Have a good weekend");
//Notification click after clear notification
builder.setAutoCancel(true);
//Set notification sound
builder.setSound(alarmSound);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
}
and MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarm();
}
private void setAlarm(){
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(MainActivity.this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_WEEK,6);
calendar.set(Calendar.HOUR_OF_DAY,16);
calendar.set(Calendar.MINUTE,53);
calendar.set(Calendar.SECOND,0);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
}
As on click on notification it open MainActivity and in onCreate method of this activity you are calling setAlarm() . So on click of notification onCreate method is invoked then setAlarm() is invoked , this again set Alarm and build notification.
Do following changes
call setAlarm() onClick of a button, so that it is not invoked automatically onCreate of activity.
If you want to send notification automatically
change the intent of notification
Intent i = new Intent(context, MainActivity.class);
As of now you are using intent to open ManinActivity on click of notification.
Change Intent to
Intent i = new Intent(context, OtherActivity.class);
OtherActivity is the activity which does not setAlarm() or build notification in onCreate method.
Alternative Method
Use sharedPreferences to check whether the notification is build once or not.
if build once then don't call setAlarm()
I have a Timer and I send a notification to the user when the timer finishes, I've added a "Stop" button to my notification and when the user clicks it I want the sound of the timer to stop.
What I tried is registering the action to my BroadcastReceiver in my TimerActivity like this:
filter = new IntentFilter();
filter.addAction(TimerService.BROADCAST_ACTION);
registerReceiver(broadcastReceiver, filter);
this is the BroadcastReceiver inside the TimerActivity:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ScheduledService.STOP_TIMER))
{
if(timerAudio.isPlaying())
{
timerAudio.stop();
timerAudio.release();
timerAudio = null;
}
}
};
And this is my how I create the notification inside the ScheduledService class:
Intent notificationIntent = new Intent(getBaseContext(), CookingTimer.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Intent nextIntent = new Intent(STOP_TIMER);
PendingIntent stopTimer = PendingIntent.getBroadcast(this, 0, nextIntent, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("This is a sample notification")
.setContentText("Subject")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.addAction(R.drawable.ic_launcher, "Stop", stopTimer).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
I've registered the Service and the action inside my Manifest and I receive the notification correctly, but the button action doesn't work.. Can someone explain me how to fix this?
Post the Activity that has the MediaPlayer controlling the sound.
If you are not receiving Null Pointer Exceptions, I suppose that timerAudio is correct.
However specify if the current view is defined and in context.
Hi I want to show alert after click on my notification. Here is code:
#SuppressWarnings("deprecation")
private void Notify(String notificationTitle, String notificationMessage) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon_stat, "Powiadomionko", System.currentTimeMillis());
notification.ledARGB = Color.CYAN;//0xFFff0000;
notification.ledOnMS = 800;
notification.ledOffMS = 2400;
notification.vibrate = new long[]{100, 120, 100, 120};
Intent notificationIntent = new Intent(this, TerminarzActivity.class);
notification.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_VIBRATE;
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(Serwis_updateTERM.this, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(1, notification);
}
And I want to show Alert on anything not on my Activity after click. Anyone know how to do this ?
I know i must add
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
but nothing else..
Check out the creation of this notification (taken from Geofence sample). This code creates a notification and if you touch it it launches your MainActivity.
// Create an explicit content Intent that starts the main Activity
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
// Construct a task stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the main Activity to the task stack as the parent
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions
// >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Set the notification contents
builder.setSmallIcon(R.drawable.ic_folder)
.setContentTitle(getString(R.string.geofence_transition_notification_title, transitionType, ids))
.setContentText(getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
// Get an instance of the Notification manager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
This code might help you, but still it depends what do you mean by "alert".
I have an activity (Musicplayer.class) which plays music and a notification is shown when the track starts playing however when I tap on the notifaction it takes me back to the main activiy (1st activiy of the app)
How do I modify the code so that tapping the notification takes me to the music player activity.
the code is taken from the android documentation ( see below )
final NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MusicPlayer.this)
// set values....
Intent resultIntent = new Intent(MusicPlayer.this, MusicPlayer.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MusicPlayer.this);
stackBuilder.addParentStack(MusicPlayer.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final int mId = 1;
mNotificationManager.notify(mId,mBuilder.build());
changed code to this:
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pendingIntent);
and now the activity duplicates (two same activities running, same music playing 2 times)
In my application, I have two main activities:
MainActivity and MessagesActivity
When the notification is clicked and the application is not running, I want it to start the MainActivity. However, when the application is running and the MessagesActivity is in view, I want when the user clicks the notification to somehow receive the intent data.
I create my notification something like this:
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra(MESSAGE_KEY, receivedMessage);
notificationIntent.putExtra(MESSAGE_ID_KEY, receivedMessageId);
int requestID = (int) System.currentTimeMillis();
PendingIntent contentIntent = PendingIntent.getActivity(context, requestID, notificationIntent, PendingIntent.FLAG_ONE_SHOT, intent.getExtras());
Notification notification = new Notification.Builder(context)
....build();
notificationManager.notify(requestID, notification);
I've tried playing around with other flags, launchModes, etc. This wouldn't be a problem if it was all just one activity but onNewIntent is never called when the application is running in either MainActivity or MessagesActivity