System notification from SyncAdapter:onPerformSync - java

I have sync adapter that performs some operation in background. To notify my main activity about sync operation status, I used broadcast receivers, so my activity is able to receive messages from sync adapter. It works fine. However, I also need to display notification on android status bar, that indicates some sync results.
So I wrote simple method reponsible to disaply system notification:
private void sendNotification(Context ctx, String message)
{
Intent intent = new Intent(ctx, this.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Mobile Shopping")
.setContentText(message)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND | Notification.FLAG_SHOW_LIGHTS)
.setLights(0xff00ff00, 300, 100)
.setPriority(Notification.PRIORITY_DEFAULT);
//.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 , notificationBuilder.build());
}
Then, above method is called in onPerform sync:
#Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult)
{
.................
sendNotification(context, message);
}
Context is retrieved from constructor. It works without any problems, notification is showing.
However I also need to show main activity after user cicks on notification. So I believe I need to create PendingIntent and pass it to my notification builder (as it's commented in my code). But to pass main activity object to my sync adapter? Notification can be also displayed after auto sync finished.
Any tips?

So, I figured it out. Solution is to create pending intent this way:
Intent notificationIntent = new Intent(ctx, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);
So after user clicks to notification, main activity will be shown.

Related

How to dismiss full screen intent to notification bar?

I am trying to display a notification about incoming call (from within my app) to a user. I found out that I can use NotificationCompat.Builder.setFullScreenIntent() to make a notification persistent on the top of the screen when application is running in the background.
However now when user does not answer the call and other party stops ringing how do I make that full screen intent disappear and show it inside a notification bar?
The only way I can think of is calling cancel() on that notification ID and creating a new one without full screen intent. But is this a good way of doing this? Is there a 'good practice' on how to achieve what I want?
Snippet showing how I create the notification:
public void displayNotification(String title, String text, int conversationId) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
this.createNotificationChannel();
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this.context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context, this.channelID);
builder.setContentTitle(title);
builder.setContentText(text);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setFullScreenIntent(pendingIntent, true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this.context);
notificationManager.notify(conversationId, builder.build());
}

Multiple notification on same intent

I am writing an application and in this application I need to set multiple notification with same intent just like open my application whenever user tap on any notification.
All the notification comes on different time and date without having any data but the problem is, if I set two notification for 03:27 PM and 03:28 PM then the first notification (03:27 PM) is canceled (Overwritten by second) and second is working correctly.
I am currently using this code for achieving this goal:
this method is used to set notification from Activity:
public static void setNotificationOnDateTime(Context context, long fireTime)
{
int requestID = (int) System.currentTimeMillis();
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, NotificationReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, requestID, i, 0);
am.set(AlarmManager.RTC_WAKEUP, fireTime, pi);
}
and my NotificationReceiver class look like this:
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
Log.w("TAG", "Notification fired...");
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent;
Bundle bundle = intent.getExtras().getBundle("NotificationBundle");
if(bundle == null)
{
contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, SplashScreen.class), 0);
}
else
{
contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MenuScreen.class)
.putExtra("NotificationBundle", bundle), 0);
}
Notification notif = new Notification(R.drawable.ic_launcher,
"Crazy About Android...", System.currentTimeMillis());
notif.setLatestEventInfo(context, "Me", "Message test", contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
I alerady spend a lot time on googling and found some solutions but they didn't work for me here is the link of some of them:
android pending intent notification problem
Multiple notifications to the same activity
If any one knows how to do this please help me.
Quote:
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
But you're always using 1 for the id parameter. Use a unique ID when you post several notifications.
Update If that doesn't help, you can still create Intents which do not compare as being equal, while having an equal effect.
this may be helpful
notif.flags |= Notification.FLAG_ONGOING_EVENT;
the notification will never close...
Try to set as below :
contentIntent=PendingIntent.getActivity(p_context, i, new Intent(context, MenuScreen.class),PendingIntent.FLAG_CANCEL_CURRENT);
It might help you.

Notifications not shown in Android Froyo

I'm trying to run the following, which is ripped from an internet tutorial:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Prepare intent which is triggered if the
// notification is selected
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
//Intent intent = new Intent(this, ReceiveAndGoHome.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, homeIntent, 0);
// Build notification
// Actions are just fake
Notification noti = new NotificationCompat.Builder(this)
.setContentTitle("Fraz Go Home!!!")
.setContentTitle("Fraz Go Home!!!")
.setContentText("Fraz Go Home!!!")
.setContentIntent(pIntent)
.addAction(R.drawable.ic_launcher, "Call", pIntent)
.addAction(R.drawable.ic_launcher, "More", pIntent)
.addAction(R.drawable.ic_launcher, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(25, noti);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
When I run the above in a froyo AVD, I do not see a notification appear at all - am I missing something obvious?
You forgot to set the small icon. Add this:
.setSmallIcon (R.drawable.ic_launcher)
somewhere in your NotificationCompat.Builder chain of methods.
Of course, the launcher drawable is what I used there since it's on hand, you will need to make actual notification icons for a proper UI. This is just to demo the method call you need.
The Android documentation outlines what you need for a Notification to show:
Required notification contents
A Notification object must contain
the following:
• A small icon, set by setSmallIcon()
• A title, set by setContentTitle()
• Detail text, set by setContentText()

Receiving notifications: on click handle for multiple activities

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

Android - GCM push notifications not appearing in notifications list

I'm working on my first Android app to use the Google Cloud Messaging (GCM) service for push notifications. I've got to the point where I can successfully send a message from my server application, and log the content of the message in the onMessage event within my GCMIntentService class on the client app. However I don't see any visual indication on the device that a message was received. I was expecting the message to appear in the pull-down notifications list on the phone, as it does on the iPhone. Does this have to be coded manually? Also is there a common method for displaying the message regardless of which activity is currently active, and if the app is idle in the background? Any help appreciated.
This code will generate a notification in the android system bar at the top of the screen. This code will create a new intent that will direct the user to a "Home.class" after clicking on the notification in the top bar. If you would like it to do something specific based on the current activity you could send broadcast requests from the GCMIntentService to your other activities.
Intent notificationIntent=new Intent(context, Home.class);
generateNotification(context, message, notificationIntent);
private static void generateNotification(Context context, String message, Intent notificationIntent) {
int icon = R.drawable.icon;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
Note that this example uses resources in R.drawable and R.String that will need to be present to work but it should give you the idea. See this for more information about status notifications http://developer.android.com/guide/topics/ui/notifiers/index.html and this about broadcast recievers. http://developer.android.com/reference/android/content/BroadcastReceiver.html
If you are using GcmListenerService you can use this code, add to your onMessageReceived the sendNotification()
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
sendNotification(message);
}
private void sendNotification(String message) {
Intent intent = new Intent(this, YOURCLASS.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_park_notification)
.setContentTitle("Ppillo Message")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

Categories

Resources