Custom notification with remote view on Android - android

I have edited the code by using setOnClick pending intent, and this code works for ImageView and notifications text seperate as I want, but I still need some help.
I want to pause or play mediaplayer from my service class, so how could I access the stop or play method of service from Notification pending intent?
Some says broadcast receivers will help you, but I don't get exactly how it's going to work.
I have managed to open a web browser from the pause button from notification, but I don't know how to access service methods. Share any sample code if you have some.
#SuppressWarnings("deprecation")
void showNotification() {
int pendingRequestCode = 0;
int pendingFlag = 0;
final Resources res = getResources();
final NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pi= PendingIntent.getActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_action_search)
.setAutoCancel(true)
.setTicker("this is notification")
.setContentIntent(pi);
// Sets a custom content view for the notification, including an image button.
RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification);
layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
Intent clickIntent = new Intent(Intent.ACTION_VIEW, Uri_myBlog);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),pendingRequestCode, clickIntent, pendingFlag);
layout.setOnClickPendingIntent(R.id.notification_button,pendingIntent);
builder.setContent(layout);
// Notifications in Android 3.0 now have a standard mechanism for displaying large
// bitmaps such as contact avatars. Here, we load an example image and resize it to the
// appropriate size for large bitmaps in notifications.
Bitmap largeIconTemp = BitmapFactory.decodeResource(res,
R.drawable.pause);
Bitmap largeIcon = Bitmap.createScaledBitmap(
largeIconTemp,
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height),
false);
largeIconTemp.recycle();
builder.setLargeIcon(largeIcon);
notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification());
}
PendingIntent getDialogPendingIntent(String dialogText) {
return PendingIntent.getActivity(
this,
dialogText.hashCode(), // Otherwise previous PendingIntents with the same
// requestCode may be overwritten.
new Intent(ACTION_DIALOG)
.putExtra(Intent.EXTRA_TEXT, dialogText)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
0);
}

You did not tell what version of Android you target, but in general it is not possible until Android 3.x (Honeycomb). So if you want that to happen on 2.x, then sorry - you are out of luck.
For Honeycomb, you simply have to provide a custom layout and assign PendingIntent to each button you need, by calling setOnClickPendingIntent(). If you got the SDK's samples downloaded, then see MainActivity of the HoneycombGallery app (shall be in your <SDK>\samples\android-XX\HoneycombGallery\ folder. XX is anything from 14 (or higher).

Check Bound Services using Messenger
http://developer.android.com/guide/components/bound-services.html
Also you can check this question
Binding to a local Service from a BroadcastReceiver

Related

Inconsistent notification actions buttons' UI even on same device

I have an app where i'm having some issues with notifications not being consistent on different devices. The notification is used by a foreground service
This is what my notification looks like in my pixel3 api29 emulator
Because of the issue i'm troubleshooting, I decided to extract the code and put it in a dummy app that would let me simulate the triggering event more easily. However, after doing that and running on the exact same pixel3 api29 emulator, i realized the notification is not even consistent on the same device. In the dummy app for a dummy foreground service the notification looks like this
I can't find what's driving the different look of the action buttons in the two apps. Even the behaviour is different. In the first version, the floating headsup notification stays there forever until i clear it programatically but in the second dummy app the notification clears itself after 6 seconds. I tried using the same theme in both, added the exact same dependency versions thinking that i was pulling different versions of the notification library but nothing, the code to create the notifications is the same in both:
private Notification createIncomingCallNotification(Intent intent) {
Intent hangupIntent = new Intent(this, getClass());
hangupIntent.setAction("hangup");
PendingIntent hangupPendingIntent = PendingIntent.getService(this, 1244, hangupIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Action hangupAction = new NotificationCompat.Action.Builder(0, getActionText(R.string.hangup_button_label, R.color.test1), hangupPendingIntent).build();
Intent uiIntent = new Intent(this, VideoCallActivity.class);
uiIntent.putExtras(intent);
uiIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, uiIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action previewAction = new NotificationCompat.Action.Builder(0, getActionText(R.string.preview, R.color.test2), fullScreenPendingIntent).build();
String caller = "Caller guy";
Log.v(TAG, "Creating incoming call notification from " + caller);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ChannelIds.INCOMING_CALL_CHANNEL_ID)
.setContentTitle(getString(R.string.incoming_call_notification_title, caller))
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setSmallIcon(R.drawable.ic_white_100dp)
.addAction(hangupAction)
.addAction(previewAction)
.setOnlyAlertOnce(true)
.setFullScreenIntent(fullScreenPendingIntent, true);
return notificationBuilder.build();
}
private Spanned getActionText(#StringRes int stringRes, #ColorRes int colourRes) {
Spannable spannable = new SpannableString(getText(stringRes));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
// This will only work for cases where the Notification.Builder has a fullscreen intent set
// Notification.Builder that does not have a full screen intent will take the color of the
// app and the following leads to a no-op.
spannable.setSpan(new ForegroundColorSpan(getColor(colourRes)), 0, spannable.length(), 0);
}
return spannable;
}
Does anyone know what can cause this inconsistency even on the same device?
I finally figured it out. What changes the headsup notification is this permission in the manifest
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>

Android: How to build a notification with a cancel button?

I am trying to create a notification with a cancel button, but when I click on it nothing happens. This is my code:
private NotificationCompat.Builder notificationBuilder;
public void createNotification() {
notificationBuilder = new NotificationCompat.Builder(service);
notificationBuilder.setProgress(100, 0, false);
notificationBuilder.setAutoCancel(true);
Intent intent = OrderProcessingService_.intent(service).actionCancelUpload(basket.getPhotobook_id()).get();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getService(service, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder.setSmallIcon(R.drawable.ic_action_file_cloud_upload);
NotificationCompat.Action cancelAction = new NotificationCompat.Action(R.drawable.ic_action_navigation_close, service.getString(R.string.cancel_upload), pendingIntent);
notificationBuilder.setContentTitle(service.getString(R.string.notification_upload_title));
notificationBuilder.setContentText(service.getString(R.string.notification_uploading_subtext, Util.getTitle(basket.getPhotobook())));
notificationBuilder.addAction(cancelAction);
addBigPicture(notificationBuilder);
service.startForeground(1, notificationBuilder.build());
}
You will have to keep notification id and then call
NotificationManager nMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancel(notification );
I am glad to post it! After working all night I found something. So, here we go!
Create an xml layout file for your notification.
Create the notification using the Notification.Builder. After adding everything you want (icons, sounds, etc) do this:
//R.layout.notification_layout is from step 1
RemoteViews contentView=new RemoteViews(ctx.getPackageName(), R.layout.notification_layout);
setListeners(contentView);//look at step 3
notification.contentView = contentView;
Create a method setListeners. Inside this method you have to write this:
//HelperActivity will be shown at step 4
Intent radio=new Intent(ctx, packagename.youractivity.class);
radio.putExtra("AN_ACTION", "do");//if necessary
PendingIntent pRadio = PendingIntent.getActivity(ctx, 0, radio, 0);
//R.id.radio is a button from the layout which is created at step 2
view.setOnClickPendingIntent(R.id.radio, pRadio);
//Follows exactly my code!
Intent volume=new Intent(ctx, tsapalos11598712.bill3050.shortcuts.helper.HelperActivity.class);
volume.putExtra("DO", "volume");
//HERE is the whole trick. Look at pVolume. I used 1 instead of 0.
PendingIntent pVolume = PendingIntent.getActivity(ctx, 1, volume, 0);
view.setOnClickPendingIntent(R.id.volume, pVolume);
For my requirements I used a HelperActivity which responds to the intents. But for you I don't think it is necessary.
If you want the full source code you can browse it or download it from my git repo. The code is for personal use, so don't expect to read a gorgeous code with a lot of comments. https://github.com/BILLyTheLiTTle/AndroidProject_Shortcuts
ALL THE ABOVE, ANSWERS THE QUESTION OF CATCHING EVENT FROM DIFFERENT BUTTONS.
About canceling the notification I redirect you here
How to clear a notification in Android
Just remember to use the id you parsed at the notify method when you called the notification for fist time
Source : Android notification with buttons on it

Android notification PendingIntent open activity per notification click

I'm currently doing some notifications for my app. Now I've successfully created a notification but problem is that each of my notification doesn't pass different extras on click.
Well what happen is that I only have a loop that calls the createNotification method per loop and also I assign different ID's for those for the notification to appear in different stack.
here's my code:
private void createNotification(String record_name, String file_path, String status, int id) {
/*must pass:
* record_name, (get the record name in DB using the id create a new query method)
* record_status, (simple part just match if equivalent to ready to download for the JSON data then show notif if true)
* record_path *full path* (this one can be get using the record name itself add the path and extension name)*/
/*this will jump from the current activity into the target activity class just do some workarounds here*/
Intent intent = new Intent(this, RecordEditActivity.class);
intent.putExtra("record_name", record_name);
intent.putExtra("record_path", file_path);
intent.putExtra("record_status", status);
PendingIntent pIntent = PendingIntent.getActivity(this,0, intent, 0);
/*build the notification here this is only supported for API 11. Since we've targeted API 11 there will be no problem on this*/
NotificationCompat.Builder notify = new NotificationCompat.Builder(this)
.setContentTitle(record_name + " is ready for download")
.setContentText("Click to view or download recording")
.setAutoCancel(true)
.setSmallIcon(R.drawable.notif_icon)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher))
.setTicker("Echo: your file is ready for download")
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT<16){
/*build notification for HoneyComb to ICS*/
notificationManager.notify(id, notify.getNotification());
}if(Build.VERSION.SDK_INT>15){
/*Notification for Jellybean and above*/
notificationManager.notify(id, notify.build());
}
}
I think the problem is in the PendingIntent part since I don't know which flags should I use for this but I'm not that sure about it.
Got it! what needed is for me to assign an ID for my pendingIntent requestCode what I did is assign the same ID I used for my notificationManager.
More info here.
Just use this one line of code-
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
And for more detail see this answer:
GCM android Push Notification shows old message always. Intent received incorrect

Android: Custom notification appearance issue

I am using MediaPlayer in my app. I am adding an Ongoing Notification with media player controls (such as previous, next and stop buttons) in my app, so that users don't have to go in the app to access those controls. It looks fine on platforms 4.x. Here is the screenshot of the notification on Android 4.2.2.
But, on Android 2.2, it looks like this:
My code is as follows:
private Notification generateNotification() {
Log.d(TAG, "generateNotification called");
Intent actionIntent = new Intent(getApplicationContext(),
AartiActivity.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews mNotificationView = new RemoteViews(getPackageName(),
R.layout.notification_view);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext());
builder.setSmallIcon(R.drawable.icon);
builder.setContent(mNotificationView);
builder.setOngoing(true);
builder.setTicker("Aarti Sangrah");
builder.setContentIntent(pi);
mNotificationView.setImageViewResource(R.id.imgAppIc, R.drawable.icon);
mNotificationView.setTextViewText(R.id.txtAartiPlaying, mediaName);
return builder.build();
}// generateNotification
And then, I called startForeground(1, generateNotification()); in onPrepared().
The Remote Views is available since API level 1. And, it is well supported also. I read somewhere, it was not supported prior to Honeycomb. But, on several devices having Android 2.x, this feature is available. Also, in order to check this, I looked at the source code of Music Player of Android 2.2 from here.
Here, is the snippet from its Music Player Service.
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.statusbar);
views.setOnClickPendingIntent(R.id.btnTest, PendingIntent
.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(),
MusicBrowserActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT));
views.setImageViewResource(R.id.icon,
R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(
R.id.artistalbum,
getString(R.string.notification_artist_album, artist,
album));
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
startForeground(PLAYBACKSERVICE_STATUS, status);
The Remote Views has been used in this code. It had two TextViews. I modified the code by adding a button to it, and also performed action on button click. Everything worked fine on every platform.
Same thing, I want with my application. But, on 2.2, it looks as I had shown above in the screenshot. I thought it is because of white colors text and button so tried changing the colors of button and text, but no luck. As far as I understand, only thing I figured out is remote view is not inflated on Android 2.2 (in my case). I am not getting why notification is not appearing properly on Android 2.x platforms.
I solved my problem. Here is my solution.
private Notification generateNotification() {
Log.d(TAG, "generateNotification called");
Intent actionIntent = new Intent(getApplicationContext(),
AartiActivity.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews mNotificationView = new RemoteViews(getPackageName(),
R.layout.notification_view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext());
builder.setSmallIcon(R.drawable.icon);
builder.setContent(mNotificationView);
builder.setOngoing(true);
builder.setTicker("Aarti Sangrah");
builder.setContentIntent(pi);
mNotificationView.setImageViewResource(R.id.imgAppIc,
R.drawable.icon);
mNotificationView.setTextViewText(R.id.txtAartiPlaying, mediaName);
mNotificationView.setTextColor(R.id.txtAartiPlaying, getResources()
.getColor(android.R.color.holo_orange_light));
return builder.build();
} else {
mNotificationView.setTextViewText(R.id.txtAartiPlaying, mediaName);
mNotificationView.setTextColor(R.id.txtAartiPlaying, getResources()
.getColor(android.R.color.holo_orange_light));
Notification statusNotification = new Notification();
statusNotification.contentView = mNotificationView;
statusNotification.flags |= Notification.FLAG_ONGOING_EVENT;
statusNotification.icon = R.drawable.icon;
statusNotification.contentIntent = PendingIntent.getActivity(this,
0, new Intent(getApplicationContext(), AartiActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
return statusNotification;
}
}// generateNotification
But, I am quiet surprised. NotificationCompat.Builder is available in support package and it has been provided for backward compatibility. But, in my case it is working only on Honeycomb and above. As per this section:
Not all notification features are available for a particular version, even though the methods to set them are in the support library class NotificationCompat.Builder. For example, action buttons, which depend on expanded notifications, only appear on Android 4.1 and higher, because expanded notifications themselves are only available on Android 4.1 and higher.
But, I don't think that, this is applicable for my case. NotificationCompat.Builder works with remote views but didn't worked on 2.x(at least in my case, may be I am wrong or missing something). If anybody has any information or resources in this regard, please share it so that I can figure out my mistake.

what to code for notification to stick until music stop playing

I want notification which will stick on notification bar until music stop playing it.
currently i have written some code in which i can show notification but when i press clear notification button or swap it than it disappear from notification center.
I want notification like spotify which stays on bar until you stop playing music.
Here is my code for notification
int pendingRequestCode = 0;
// final Resources res = getResources();
notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
Intent i = new Intent(getApplicationContext(),Mainactivity.class);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_action_search)
.setAutoCancel(true)
.setTicker("test ckick")
.setContentIntent(PendingIntent.getActivity(getApplicationContext(), NOTIFICATION_DEFAULT, i,0));
// Sets a custom content view for the notification, including an image button.
layout = new RemoteViews(getPackageName(), R.layout.notification);
layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
Intent clickIntent = new Intent();
clickIntent.setAction(ACTION_DIALOG);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), pendingRequestCode, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
layout.setOnClickPendingIntent(R.id.notification_button,pendingIntent);
builder.setContent(layout);
// Notifications in Android 3.0 now have a standard mechanism for displaying large
// bitmaps such as contact avatars. Here, we load an example image and resize it to the
// appropriate size for large bitmaps in notifications.
layout.setImageViewResource(R.id.notification_button, R.drawable.pause);
notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification());
waiting for reply
Use setOngoing(true) to indicate that the event is ongoing. You may also wish to remove setAutoCancel(true), as that clears the Notification when the user taps upon it.
notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL

Categories

Resources