Android Specific Notification Sound Chosen By User In App - android

In my app I have bundled a custom unique sound for push notifications with FirebaseMessagingService.
I have also built in the ability for the user to choose their own custom sound.
With the below code if the use IS IN THE APP: the user chosen sound will play if they chose one. BUT if out of the application, my custom unique sound will play.
I would like for the users selected custom notification sound (if they chose one) to play if they are not using the app instead of my unique sound.
I have stored the Ringtone sound URI in a preferences file: content://media/internal/audio/media/57
public class MyAppFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCMService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification().getBody());
}
}
private void sendNotification(final String messageBody) {
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = null;
if (AppPref.getUserWantsCustomSound()){
//ANDROID SOUND CHOSEN BY USER
defaultSoundUri = Uri.parse(AppPref.getUserCustomSound()); // Returns content://media/internal/audio/media/57
} else {
//PRE PACKAGED SOUND included in app
defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pushnotify);
}
Log.d(TAG, "defaultSoundUri: " + defaultSoundUri);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My App")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
//IF IN APP SHOW A TOAST MESSAGE
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),messageBody,Toast.LENGTH_SHORT).show();
}
});
}
}

If you need to differ on client side whether app is either in foreground or background, try to implement an interface ActivityLifecycleCallbacks by your Application class and set a flag once you app is going to background.
public class App extends Application implements Application.ActivityLifecycleCallbacks {
private static boolean isBackground = false;
#Override
public void onActivityStarted(Activity activity) {
isBackground = false;
}
#Override
public void onActivityStopped(Activity activity) {
isBackground = true;
}
public static boolean isInBackground(){
return this.isBackground;
}
}
Also, don't forget to define this custom application class in your AndroidManifest.xml file.
<application
android:name=".App">
</application>
Lastly, in your push notification code:
if (AppPref.getUserWantsCustomSound() && !App.isInBackground()){
//ANDROID SOUND CHOSEN BY USER
defaultSoundUri = Uri.parse(AppPref.getUserCustomSound()); // Returns content://media/internal/audio/media/57
} else {
//PRE PACKAGED SOUND included in app
defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pushnotify);
}

Related

FCM Tap on how to open a User specified activity instead of default activity when app is in background state

The FCM is working fine and notification came on device when app is in foreground state, and when tapped on notification, it is redirecting to my specified Activity, so it is working fine.
But my challenge is when the notification comes when app is in background state and when tapped, it redirects to Default Activity but I want to navigate to specified activity.
Here is MyFirebaseMessagingService class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private String title, messageBody;
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (remoteMessage.getData() != null && remoteMessage.getData().size() > 0) {
title = remoteMessage.getData().get("title");
if (TextUtils.isEmpty(title)) title = "Bocawest";
messageBody = remoteMessage.getData().get("message");
}
handleNow();
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
if (!TextUtils.isEmpty(messageBody))
sendNotification(title, messageBody);
//sendNotification(remoteMessage.getNotification().getBody());
Intent intent = new Intent();
intent.setAction("com.android.bocawest");
sendBroadcast(intent);
}
// [END receive_message]
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String title, String messageBody) {
PendingIntent pendingIntent;
if (SharedPreference.getBoolean(getApplicationContext(), getApplicationContext().getResources().getString(R.string.sp_isLoginIN))) {
Intent intent = new Intent(this, NotificationsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
} else {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Bocawest",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
}
Note : NotificationsActivity is my specified activity.
HomeActivity is Default Activity
I know there are lot of similar questions but I haven't found anything specific to my usecase.
Please Help me.
#Laxman parlapelly as per Firebase standered when your app receive notification in background and user tap on notification then it will open default activity only.
If you want to open your specified activity then you have to pass through your default activity only.
For example in your case when user tap on notification it will open your Home activity and from oncreate method of HomeActivity you need to open NotificationsActivity(along with bundle incase needed)
When
Notification is tapped when app is in background then onCreate() method of HomeActivity will be called so with in that you can write code to open Notification Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
animLay = findViewById(R.id.root_lay_la);
Intent intent = new Intent(this,NotificationActivity.class);
//intent.putExtra("KEY",getIntent().getStringExtra("data")); if u need to pass data
startActivity(intent);
}
if(SharedPreference.getBoolean(getApplicationContext(), getApplicationContext().getResources().getString(R.string.sp_isLoginIN))) write this logic in HomeActivity(in onCreate() before setContentView()) so every time user will be re-directed to HomeActivity and if the above condition satisfies the user will be redirected again to NotificationsActivity else will continue with HomeActivity
check - Navigate to different activities on notification click
this works for me
- just add the code below inside onMessageReceived()
Intent intent = new Intent(this, NotificationsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "111")
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.yhnn))
.setContentText(title)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setSound(sound)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(5, builder.build());

Android Auto notification not showing

I'm attempting to show a notification through Android Auto. The notification does show on my phone. However, it is not showing on Android Auto emulator. This is a media application.
automotvie_app_desc.xml:
<automotiveApp>
<uses name="media"/>
</automotiveApp>
This code is in my MediaBrowserService class:
private Notification postNotification(AutoNotificationHelper.Type type) {
Log.d(TAG, "Post Notification");
Notification notification = AutoNotificationHelper.createMenuErrorNotification(
getApplicationContext(), type, mSession);
if (notification != null) {
mNotificationManager.notify(TAG, NOTIFICATION_ID, notification);
}
return notification;
}
Here is where the notification is created:
static Notification createMenuErrorNotification(Context context, Type type,
MediaSessionCompat mediaSession) {
MediaControllerCompat controller = mediaSession.getController();
MediaMetadataCompat mMetadata = controller.getMetadata();
PlaybackStateCompat mPlaybackState = controller.getPlaybackState();
if (mMetadata == null) {
Log.e(TAG, "MetaData is null");
}
if (mPlaybackState == null) {
Log.e(TAG, "Playback state is null");
}
if (type.equals(Type.MENU_ERROR)) {
Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.error);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context.getApplicationContext());
notificationBuilder.extend(new android.support.v4.app.NotificationCompat.CarExtender())
.setStyle(new NotificationCompat.MediaStyle()
.setMediaSession(mediaSession.getSessionToken()))
.setSmallIcon(R.drawable.error)
.setShowWhen(false)
.setContentTitle(context.getString(R.string.title))
.setContentText(context.getString(R.string.message))
.setLargeIcon(icon)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
return notificationBuilder.build();
}
return null;
}
What am I missing to get this to show on the auto display and not on the phone?
NotificationCompat.CarExtender seems to be an option only for app declare as "notification" (message read and response feature for a messaging app for example).
<automotiveApp>
<uses name="notification"/>
</automotiveApp>
Display notification on home in "Auto" context with a "media" automotiveApp seems not allowed in actual api version.
For an error message associated to a media playing app (like it seems to be in your case) you can use error state which will be interpreted and displayed directly by Auto system.
private void showErrorMessage(final int errorCode, final String errorMessage) {
final PlaybackStateCompat.Builder playbackStateBuilder = new PlaybackStateCompat.Builder();
playbackStateBuilder.setState(PlaybackStateCompat.STATE_ERROR, -1L, 1.0F);
playbackStateBuilder.setErrorMessage(errorCode, errorMessage);
mSession.setPlaybackState(playbackStateBuilder.build());
}
Try this code to show the notification,
private void showPushNotification(String title, String message, Intent tapIntent, int notificationID) {
android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.swiftee_white_logo_notification);
//Intent tapIntent = new Intent(this, HomeScreenActivity.class);
//tapIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//tapIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//tapIntent.putExtra(AppConstants.PUSH_MESSAGE, true);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, tapIntent, PendingIntent.FLAG_ONE_SHOT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
builder.setContentTitle(title);
builder.setContentText(message);
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationID, builder.build());
}
Please follow step by step from here
This sample demonstrate full demo
EDIT
For Media Notification you can use this . Here step by step explained about media app and notification for auto

Customize firebase notification

I have an Chat app in which a user is subscribed to an topic and each group is a topic. Whenever an message is sent in the group. An notification is sent to that topic.
There are two problems that I am facing.
When the sender sends the message in the group, a notification message is sent to the topic. But before the user gets the notification from firebase, He closes the application or the app goes in the background. So According to the firebase documentations, the notification is sent to the notification tray and not the onMessageReceived callback.
The notification that is received from the firebase is added to the tray. How can the users other than the sender get the notification Id so that i can be cancelled when it required. How can this notification be customised?
Is there a way to keep an active listener for receiving the notification when the app is in the background or terminated.
Please help
You might wan to take a look this.At first I always have problem reading the doc due to english not my primary language. It very confuse but just follow the step you will get more understading.
For your first question you do not need to use both notification and data message. If you use so it will prevent onMessageReceived() get call if the app is in foreground or force close. Trust me just remove the notification{notification:"data"} but keep {data:"something"} while sending to firebase. It will always trigger onMessageReceived().
For you second question after you follow the step above you won't get any notification display on your status bar. Here you can check wether this user is the sender, if it wasn't the sender then you can just show your custom notification inside onMessageReceived().
You can push notification to your app for user engaging with fire base by sending notification,when your app is closed,on basis of some parameters go to fire base .
Make sure Your Project is Added in Fire base first before doing this at all:otherwise add your project in fire base with package name,fingerprint and google_services.json file in app folder of your project .
Fire base Cloud Messaging
it will push notification to your app, if its closed then it let the user to open the app via notification pressed, and if you wants to show notification to the user to direct to another apps of the same account , when the app will be in use both will happened with this code:
Create you first class MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
private static final String ADMIN_CHANNEL_ID ="admin_channel";
private NotificationManager notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size()>0){
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(remoteMessage.getData().get("applink")));
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
0 /* Request code */, notificationIntent,
PendingIntent.FLAG_ONE_SHOT);
int notificationId = new Random().nextInt(60000);
Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("imageurl"));
Intent likeIntent = new Intent(this,LikeService.class);
likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("message"));
PendingIntent likePendingIntent = PendingIntent.getService(this,
notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getData().get("title"))
.setStyle(new NotificationCompat.BigPictureStyle()
.setSummaryText(remoteMessage.getData().get("message"))
.bigPicture(bitmap))/*Notification with Image*/
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.addAction(R.drawable.icon,
getString(R.string.notification_add_to_cart_button),likePendingIntent)
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(){
CharSequence adminChannelName = getString(R.string.notifications_admin_channel_name);
String adminChannelDescription = getString(R.string.notifications_admin_channel_description);
NotificationChannel adminChannel;
adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW);
adminChannel.setDescription(adminChannelDescription);
adminChannel.enableLights(true);
adminChannel.setLightColor(Color.RED);
adminChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(adminChannel);
}
}
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Create another class FirebaseIDService to get instance id service of fire base
public class FirebaseIDService extends FirebaseInstanceIdService {
public static final String FIREBASE_TOKEN = "firebase token";
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
preferences.edit().putString(FIREBASE_TOKEN, refreshedToken).apply();
}
Make class Name LikeService
public class LikeService extends Service {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
To Support Notification at Oreo with firebase dont forget to create Channels and this channels initialize in your First Launcher Activity.
in oncreate of your project first launcher activity include these channels;
String channelId = "1";
String channel2 = "2";
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
Now you have to put your Firebase service class in Mainfest under application tag:
<service android:name=".activities.services.MyFirebaseMessagingService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
<service android:name=".activities.services.FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Now run your app on your device before push notification with fire base make sure your code is integrated correctly then run app: and go to fire base cloud messaging:
put data as in photo according to your app: when its closed:
if your app is in use then your data written in advance option will show, its data about your promotional app of the same account, don use another account app here,
make sure your key should be like in above class as onMessagede Recieved in MyFirebaseMessagingService class
like
title ,message,applink,imageurl

Do not show notification if it is already shown

In my application I want show a notification in some cases.
When notification is active I do not want to create notification again.
I have activity recognition in my app and when it's detected that I am in car it starts to sound notification every second.
How could I prevent a new build notification if there is at least one active notification there?
Here is my code what I tried:
Intent closeIntent;
Intent showIntent;
if (isStart){
closeIntent = new Intent(this, SwitchButtonListener1.class);
} else {
closeIntent = new Intent(this, SwitchButtonListener2.class);
}
closeIntent.setAction("No");
PendingIntent pendingIntentClose = PendingIntent.getBroadcast(this, 0,
closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action closeAction = new NotificationCompat.Action(R.drawable.btn_close_gray, "No", pendingIntentClose);
if (isStart){
showIntent = new Intent(this, SwitchButtonListener1.class);
} else {
showIntent = new Intent(this, SwitchButtonListener2.class);
}
showIntent.setAction("Yes");
PendingIntent pendingIntentShow = PendingIntent.getBroadcast(this, 0,
showIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action showAction = new NotificationCompat.Action(R.drawable.ic_tick, "Yes", pendingIntentShow);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_stat_milebox)
.setContentTitle(title)
.setContentText(message)
.addAction(showAction)
.addAction(closeAction);
builder.setSound(alarmSound);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(100, builder.build());
Though it is an old question, but I think this answer might help others in the future:
In a case like this, when the user needs to be notified only once and the event is ongoing then using .setOnlyAlertOnce(true) and setOngoing(true) with the builder will solve the problem.
Documentation:
setOnlyAlertOnce(true): Set this flag if you would only like the sound, vibrate and ticker to be played if the notification is not already showing.
setOngoing(true): Set whether this is an ongoing notification. Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them. They are typically used to indicate a background task that the user is actively engaged with (e.g., playing music) or is pending in some way and therefore occupying the device (e.g., a file download, sync operation, active network connection).
Notification notification = new NotificationCompat.Builder(this, notificationChannel.getId())
.....
.....
.setOngoing(true)
.setOnlyAlertOnce(true)
.....
.....
.build();
Objects.requireNonNull(notificationManager).notify(notificationId, notification);
You can try the following as a sketch:
public class MediaNotificationManager extends BroadcastReceiver {
private final NotificationManager mNotificationManager;
private Context ctx;
private boolean mStarted = false;
public MediaNotificationManager(Context ctx) {
mCtx = ctx;
mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
// Cancel all notifications to handle the case where the Service was killed and
// restarted by the system.
mNotificationManager.cancelAll();
}
/**
* Posts the notification and starts tracking the session to keep it
* updated. The notification will automatically be removed if the session is
* destroyed before {#link #stopNotification} is called.
*/
public void startNotification() {
if (!mStarted) {
// The notification must be updated after setting started to true
Notification notification = createNotification();
if (notification != null) {
mStarted = true;
}
}
}
/**
* Removes the notification and stops tracking the session. If the session
* was destroyed this has no effect.
*/
public void stopNotification() {
if (mStarted) {
mStarted = false;
try {
mNotificationManager.cancel(NOTIFICATION_ID);
} catch (IllegalArgumentException ex) {
// ignore if the receiver is not registered.
}
}
}
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
LogHelper.d(TAG, "Received intent with action " + action);
switch (action) {
//do something with this.
}
}
private Notification createNotification() {
//create and return the notification
}
}
For a bit more read this:
I also used this notification in my code:
https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/mobile/src/main/java/com/example/android/uamp/MediaNotificationManager.java

Parse.com - Android custom push notification sound

I know that push notification sound, in Android, can be customised (on iOS already working).
However, I don't see any reference in the docs, only per iOS custom sound.
I saw in Parse.com forum that such a feature was requested about a year ago and answered that it was "on the table".
Any updates regarding that? If not "officially" supported, any known workaround to get it working?
I figured out a solution. This is not available through Parse's API yet but they do have documentation which explains how to extend their ParsePushBroadcastReceiver.
So create a class which extends the ParsePushBroadcastReceiver, and onReceive call a method generateNotification and write the custom code to create a custom notification of your own there. This way, you can include a sound. First of all, you would need to add the new sound file (ex mp3) to a raw directory in the resources / res folder.
By the way, don't forget to change the ParsePushBroadcastReceiver receiver from the manifest to reflect your new file. Example:
<receiver android:name="com.parse.ParsePushBroadcastReceiver"
android:exported="false">
to
<receiver android:name="com.*my_package_name*.MyBroadcastReceiver"
android:exported="false">
Here's my code. It works and it's reusable.
public class MyBroadcastReceiver extends ParsePushBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
String jsonData = intent.getExtras().getString("com.parse.Data");
JSONObject json = new JSONObject(jsonData);
String title = null;
if(json.has("title")) {
title = json.getString("title");
}
String message = null;
if(json.has("alert")) {
message = json.getString("alert");
}
if(message != null) {
generateNotification(context, title, message);
}
} catch(Exception e) {
Log.e("NOTIF ERROR", e.toString());
}
}
private void generateNotification(Context context, String title, String message) {
Intent intent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager mNotifM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(title == null) {
title = context.getResources().getString(R.string.app_name);
}
final NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.addAction(0, "View", contentIntent)
.setAutoCancel(true)
.setDefaults(new NotificationCompat().DEFAULT_VIBRATE)
.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.whistle));
mBuilder.setContentIntent(contentIntent);
mNotifM.notify(NOTIFICATION_ID, mBuilder.build());
}
}
At the end of this tutorial is explained how to play custom sounds on the push notifications.
It is done using this line:
notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
Another option to provide sound without having to generate your own notification is to just add a sound to the notification that Parse already creates for you like this:
public class MyParsePushBroadcastReceiver extends ParsePushBroadcastReceiver {
#Override
protected Notification getNotification(Context context, Intent intent) {
Notification n = super.getNotification(context, intent);
n.sound = Uri.parse("android.resource://" + context.getPackageName() + "/some_sound.mp3");
return n;
}
}

Categories

Resources