Custom Notification for incoming call not showing in android - java

I am trying to make a custom incoming call notification like WhatsApp for my app if I don't use this custom layout then my notification is working. I am trying this for the first time any help will be appreciated.
This is my FireBaseMessagingService Class
public class MyFireBaseMessagingService extends FirebaseMessagingService {
private String CHANNEL_ID = "channel-02";
private String CHANNEL_NAME = "Channel Ring";
long[] pattern = {500, 500, 500, 500, 500, 500, 500, 500, 500};
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
Log.e("NewToken", s);
getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
}
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.e("Notification", remoteMessage.getFrom());
showSimpleNotification(getApplicationContext(), remoteMessage, remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
}
public static String getToken(Context context) {
return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
}
#SuppressLint("RemoteViewLayout")
#RequiresApi(api = Build.VERSION_CODES.P)
public void showFullScreenIntent(RemoteMessage remoteMessage, String title, String body) {
Intent receiveCallIntent = new Intent(getApplicationContext(), FCMReceiver.class);
receiveCallIntent.putExtra("appointment_id", remoteMessage.getData().get("appointment_id"));
receiveCallIntent.putExtra("message", title);
receiveCallIntent.setAction("RECEIVE_CALL");
Intent cancelCallIntent = new Intent(getApplicationContext(), FCMReceiver.class);
receiveCallIntent.putExtra("appointment_id", remoteMessage.getData().get("appointment_id"));
receiveCallIntent.putExtra("message", "Call Rejected");
receiveCallIntent.setAction("CANCEL_CALL");
PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1200,
receiveCallIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1201,
cancelCallIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_call_notification);
remoteViews.setImageViewResource(R.id.caller_image, R.drawable.icon);
remoteViews.setTextViewText(R.id.caller_name, body);
remoteViews.setTextViewText(R.id.call_type, title);
remoteViews.setOnClickPendingIntent(R.id.btnAccept, receiveCallPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.btnDecline, cancelCallPendingIntent);
#SuppressLint("ResourceAsColor") NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(remoteViews)
.setCustomHeadsUpContentView(remoteViews)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setTimeoutAfter(30000)
.setOngoing(true)
.setVibrate(pattern)
.setSound(ringtone)
.setFullScreenIntent(receiveCallPendingIntent, true);
NotificationChannel channel = createChannel();
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
Notification incomingCallNotification = notificationBuilder.build();
mNotificationManager.createNotificationChannel(channel);
mNotificationManager.notify(120, incomingCallNotification);
}
This is my channel
public NotificationChannel createChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setDescription("Call Notifications");
channel.setSound(Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.ringtone),
new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_RING)
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).build());
channel.shouldVibrate();
channel.enableVibration(true);
channel.setVibrationPattern(pattern);
Objects.requireNonNull(getApplicationContext().getSystemService(NotificationManager.class)).createNotificationChannel(channel);
return channel;
}
return null;
}
This is my FCMReceiver Class
public class FCMReceiver extends BroadcastReceiver {
private Context mContext;
private String mTitle;
private String mContent;
String action = "";
#Override
public void onReceive(Context context, Intent intent) {
if (context != null) {
mContext = context;
}
Log.e("Receiver", "Receiver a notification");
mTitle = intent.getStringExtra("message");
if (mTitle != null && !mTitle.isEmpty()) {
Log.e("action", "message : " + mTitle);
performActionClicks(context, mTitle, intent);
Intent iclose = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(iclose);
context.stopService(new Intent(context, MyFireBaseMessagingService.class));
}
if (intent.getStringExtra("gcm.notification.title") != null) {
if (intent.getStringExtra("gcm.notification title").equalsIgnoreCase("New Appointment")) {
ActivityManager.RunningAppProcessInfo myProcess = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(myProcess);
boolean isInBackground = myProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
if (isInBackground) {
Intent launchIntent = new Intent(context, HomeActivity.class);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchIntent.putExtra("appointment_id", intent.getStringExtra("appointment_id"));
}
}
}
if (intent.getStringExtra("notification") != null) {
}
}
private void performActionClicks(Context context, #NonNull String mTitle, Intent intent) {
if (!mTitle.isEmpty()) {
if (mTitle.equalsIgnoreCase("Ringing")) {
Intent intentCallReceive = new Intent(context, VideoChatViewActivity.class)
.putExtra("appointment_id", intent.getStringExtra("appointment_id"));
intentCallReceive.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(intentCallReceive);
NotificationManagerCompat.from(mContext).cancel(null, 120);
} else if (mTitle.equalsIgnoreCase("Declined")) {
} else if (mTitle.equalsIgnoreCase("Call Rejected")) {
NotificationManagerCompat.from(mContext).cancel(null, 120);
}
}
}

In you NotificationBuilder you need to set notification category to NotificationCompat.CATEGORY_CALL and style to NotificationCompat.BigTextStyle() like this
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(remoteViews)
.setCustomHeadsUpContentView(remoteViews)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setTimeoutAfter(30000)
.setStyle(NotificationCompat.BigTextStyle())
.setCategory(NotificationCompat.CATEGORY_CALL)
.setOngoing(true)
.setVibrate(pattern)
.setSound(ringtone)
.setFullScreenIntent(receiveCallPendingIntent, true);

Related

How to counter firebase notification badge android

I want firebase notification badge count. public void onMessageReceived(#NonNull RemoteMessage remoteMessage) { onMessageReceived are notifications coming from firebase. Post_id, title etc. Notifications are coming
` public class MyFirebaseMessageService extends FirebaseMessagingService {
#Override
public void onNewToken(#NonNull String token) {
super.onNewToken(token);
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
Map<String, String> data = remoteMessage.getData();
Log.d("onMessageFirebase: ", remoteMessage.getData().toString());
if (data.get("post_id") != null) {
String _unique_id = data.get("unique_id");
String title = data.get("title");
String message = data.get("message");
String big_image = data.get("big_image");
String link = data.get("link");
String _post_id = data.get("post_id");
assert _unique_id != null;
long unique_id = Long.parseLong(_unique_id);
assert _post_id != null;
long post_id = Long.parseLong(_post_id);
createNotification(unique_id, title, message, big_image, link, post_id);
}
}
}
private void createNotification(long unique_id, String title, String message, String image_url, String link, long post_id) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("unique_id", unique_id);
intent.putExtra("post_id", post_id);
intent.putExtra("title", title);
intent.putExtra("link", link);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = getApplicationContext().getString(R.string.app_name);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(getNotificationIcon(notificationBuilder))
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification_large_icon))
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
} else {
notificationBuilder.setPriority(NotificationManager.IMPORTANCE_HIGH);
}
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder.setSound(alarmSound).setVibrate(new long[]{100, 200, 300, 400});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.shouldShowLights();
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(false);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
}
if (image_url != null && !image_url.isEmpty()) {
Bitmap image = fetchBitmap(image_url);
if (image != null) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image));
}
}
//assert notificationManager != null;
notificationManager.notify((int) post_id, notificationBuilder.build());
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
return R.drawable.ic_stat_onesignal_default;
}
private Bitmap fetchBitmap(String src) {
try {
if (src != null) {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setConnectTimeout(1200000);
connection.setReadTimeout(1200000);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
}
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
}
How to counter firebase notification badge android

How I can call BroadcastReceiver from intent service?

I am trying to call BroadcastReceiver from intent service but it is never called:
public class IntentServiceTest extends IntentService {
public IntentServiceTest() {
super("IntentServiceTest");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(#Nullable Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
while (true) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Brodcast brodcast;
brodcast = new Brodcast();
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(brodcast, intentFilter);
}
}
}
Here is my BroadcastReceiver:
public class Brodcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "BroadcastReceiver", Toast.LENGTH_SHORT).show();
String NOTIFICATION_CHANNEL_ID = "100";
String channelName = "My back";
NotificationChannel channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(channel);
}
BluetoothAdapter bluetoothAdapter;
ArrayList<String> arrayList;
BluetoothDevice device;
NotificationManagerCompat notificationManagerCompat;
notificationManagerCompat = NotificationManagerCompat.from(context);
arrayList = new ArrayList<>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (!arrayList.contains(device.getName())) {
arrayList.add(device.getName());
if (arrayList.size() >= 0) {
Toast.makeText(context, "s", Toast.LENGTH_SHORT).show();
}
}
Intent i = new Intent(context, MainActivity3.class);
i.putExtra("noti", NOTIFICATION_CHANNEL_ID);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder n = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification notification = n.setOngoing(true)
.setSmallIcon(R.drawable.ss)
.setContentTitle(arrayList.size() + device.getName())
.addAction(R.drawable.as, "Action", pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("App running"))
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
notificationManagerCompat.notify(1 , notification);
}
}
}
I need to call broadcast every 20 min; can anyone help me?

android service always running and notify user when needed

I need a service to make a notification whenever the user is in a moving car.
I use ActivityRecognition to find out when the user is in a car.the issue is I need my service to run even when the app is destroyed or removed by the user.
I tried running the service on a different process but after a few minutes the service stops working.I also tried using foreground service but I had the same issue with that to.
this is my service class.
public class SpeedCheckerService extends Service {
private final String CHANNEL_ID = "my_channel";
private static SpeedCheckerService speedCheckerService;
private ActivityRecognitionClient mActivityRecognitionClient;
private boolean started = false;
Date lastNotification;
CountDownTimer countDownTimer;
Intent intent;
#Override
public void onCreate() {
createNotificationChannel();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
this.intent=intent;
countDownTimer = new CountDownTimer(99999999,1000 * 60 * 1) {
#Override
public void onTick(long l) {
recognizeActivity();
}
#Override
public void onFinish() {
countDownTimer.start();
}
}.start();
return START_STICKY;
}
String detectedActivitiesToJson(ArrayList<DetectedActivity> detectedActivitiesList) {
Type type = new TypeToken<ArrayList<DetectedActivity>>() {}.getType();
System.out.println(detectedActivitiesList.toString());
if ((detectedActivitiesList.size()>=1)&&(detectedActivitiesList.get(0).getType() == DetectedActivity.STILL) && (detectedActivitiesList.get(0).getConfidence()) >= 60){
if(lastNotification!=null){
Calendar calendar = Calendar.getInstance();
calendar.setTime(lastNotification);
calendar.add(Calendar.MINUTE,5);
Date newDate = calendar.getTime();
calendar.clear();
System.out.println(lastNotification.toString());
System.out.println(newDate.toString());
if(newDate.after(calendar.getTime()) == true)
return null;
}
speedCheckerService.makeNotification();
lastNotification = Calendar.getInstance().getTime();
}
return new Gson().toJson(detectedActivitiesList, type);
}
public void makeNotification() {
createNotificationChannel();
Intent intent = new Intent(this, MainActivity.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, CHANNEL_ID)
.setContentTitle("title")
.setContentText("text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.mapbox_logo_icon)
.setColor(Color.parseColor("#00ff00"))
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(70, builder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "guardian";
String description = "alerting user";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void recognizeActivity() {
if((mActivityRecognitionClient==null)&&(!started))
{
mActivityRecognitionClient = new ActivityRecognitionClient(this);
mActivityRecognitionClient.requestActivityUpdates(0, PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
started = true;
}
speedCheckerService =this;
if(ActivityRecognitionResult.hasResult(intent))
{
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
detectedActivitiesToJson(detectedActivities);
}
}
}
I would greatly appreciate if you can help me with my problem
Use foreground service instead of normal service and do the below changes
public class SampleService extends Service {
private NotificationManager mNotificationManager;
/**
* The identifier for the notification displayed for the foreground service.
*/
private static final int NOTIFICATION_ID = 1231234;
static void startService(Context context, String message) {
Intent startIntent = new Intent(context, SampleService.class);
startIntent.putExtra("inputExtra", message);
ContextCompat.startForegroundService(context, startIntent);
}
static void stopService(Context context) {
Intent stopIntent = new Intent(context, SampleService.class);
context.stopService(stopIntent);
}
private void createNotificationChannel() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence name = "Sample Notification";
// Create the channel for the notification
NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name,
NotificationManager.IMPORTANCE_DEFAULT);
mChannel.setSound(null, null);
// Set the Notification Channel for the Notification Manager.
notificationManager.createNotificationChannel(mChannel);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("Service", "onCreate");
createNotificationChannel();
mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Service", "onStartCommand");
startForeground(NOTIFICATION_ID, getNotification(message);
**// This is important, When your service got killed it will try to restart //the service. But some android vendor phones are restricted this autostart**
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Service", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("Service", "onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
private Notification getNotification(String contentMessage) {
String title = getString(R.string.notification_title,
DateFormat.getDateTimeInstance().format(new Date()));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
NOTIFICATION_CHANNEL_ID).setContentTitle(title).setContentText(contentMessage)
.setSmallIcon(R.drawable.notification)
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
.setTicker(contentMessage)
.setAutoCancel(false)
.setWhen(System.currentTimeMillis());
return builder.build();
}
/**
* Returns true if this is a foreground service.
*
* #param context The {#link Context}.
*/
public boolean serviceIsRunningInForeground(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(
Integer.MAX_VALUE)) {
if (getClass().getName().equals(service.service.getClassName())){
if (service.foreground){
return true;
}
}
}
return false;
}
}
You should use Foreground Service if you want service running even your app is in background or closed
https://androidwave.com/foreground-service-android-example/

fcm notification crash only with api 26

Android fcm notification is being received on android with APIs lower than 26 however APIs 26(Oreo 8.0) it doesn't and it cause app to be crashed
====================MyFirebaseMessagingService===============================
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String channel_id = "the_id";
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
updateTokenToFirebase(s);
}
private void updateTokenToFirebase(String token) {
IDrinkShopAPI mService = Common.getAPI();
mService.updateToken("SERVER_01",token,"0")
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d("DEBUG_TOKEN",response.body());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("DEBUG_TOKEN",t.getMessage());
}
});
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if(remoteMessage.getData() != null){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
sendNotification26(remoteMessage);
else
sendNotification(remoteMessage);
}
}
private void sendNotification26(RemoteMessage remoteMessage) {
Map<String,String> data = remoteMessage.getData();
String title = data.get("title");
String message = data.get("message");
NotificationHelper helper ;
Notification.Builder builder;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
helper = new NotificationHelper(this);
builder = helper.getDrinkShopNotification(title,message,defaultSoundUri);
helper.getManager().notify(new Random().nextInt(),builder.build());
}
private void sendNotification(RemoteMessage remoteMessage) {
Map<String,String> data = remoteMessage.getData();
String title = data.get("title");
String message = data.get("message");
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setSound(defaultSoundUri);
NotificationManager mn =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mn.notify(new Random().nextInt(),builder.build());
}
}
=========================NotificationHelper =================================
//this class is used to implement notification for APIs 26+
public class NotificationHelper extends ContextWrapper {
private static final String CHANNEL_ID = "the_id";
private static final String CHANNEL_NAME = "Drink_Shop";
private NotificationManager notificationManager;
public NotificationHelper(Context base) {
super(base);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
createChannel();
}
#TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel nc = new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
nc.enableLights(false);
nc.enableVibration(true);
nc.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getManager().createNotificationChannel(nc);
}
public NotificationManager getManager() {
if(notificationManager == null)
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager;
}
#TargetApi(Build.VERSION_CODES.O)
public Notification.Builder getDrinkShopNotification(String title,
String message,
Uri soundUri)
{
return new Notification.Builder(getApplicationContext(),CHANNEL_ID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(soundUri)
.setChannelId(CHANNEL_ID)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setAutoCancel(true);
}
}
=============================Manifest=======================================
<service
android:name=".Services.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
============================Build.gradle====================================
implementation 'com.google.firebase:firebase-messaging:20.0.0'
implementation 'com.google.firebase:firebase-core:17.2.1'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
===========================IFCMService=======================================
public interface IFCMService {
#Headers({
"Content-Type:application/json",
"Authorization:mytoken"
})
#POST("fcm/send")
Call<MyResponse> sendNotification(#Body DataMessage body);
}
==========================sendNotificationToServer===============================
// this method used to send the notification to server app
private void sendNotificationToServer(OrderResult orderResult) {
mService.getToken("SERVER_01", "1")
.enqueue(new Callback<Token>() {
#Override
public void onResponse(Call<Token> call, Response<Token> response) {
Map<String,String> contentSend = new HashMap<>();
contentSend.put("title","NEW ORDER");
contentSend.put("message","You have got new order" + orderResult.getOrderId());
DataMessage dataMessage = new DataMessage();
if(response.body().getToken() != null)
dataMessage.setTo(response.body().getToken());
dataMessage.setData(contentSend);
IFCMService ifcmService = Common.getFCMService();
ifcmService.sendNotification(dataMessage)
.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if(response.code() == 200){
if(response.body().success == 1){
Toast.makeText(CartActivity.this,
getResources().getString(R.string.order_submitted), Toast.LENGTH_SHORT)
.show();
//Clear Carts From Room Database
Common.cartRepository.emptyCart();
//finish();
}
else {
Toast.makeText(CartActivity.this, "Send Notification Failed", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(CartActivity.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onFailure(Call<Token> call, Throwable t) {
Toast.makeText(CartActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I think you are making the code unnecessarily complicated.
Try this below code
private void createNotification(String title, String message) {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// only create notification channel if SDK >= 26
if (android.os.Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(false);
channel.enableVibration(true);
channel.setDescription(CHANNEL_DESC);
manager.createNotificationChannel(channel);
}
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_notify_more)
.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(defaultSoundUri)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentText(message);
manager.notify(new Random().nextInt(), builder.build());
}

parse custom push sound

Sorry for my english. I use parse.com i want create custom sound when i get push. When I send a push, the phone just vibrates. There is no sound and the message does not show too.
This is my sound: image (i have not 15 reputation)
code:
public class MyBroadcastReceiver extends ParsePushBroadcastReceiver {
private int NOTIFICATION_ID = 1;
#Override
public void onPushOpen(Context context, Intent intent) {
Intent i = new Intent(context, MainActivity.class);
i.putExtras(intent.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
#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() + "/beep1.mp3"));
mBuilder.setContentIntent(contentIntent);
mNotifM.notify(NOTIFICATION_ID, mBuilder.build());
}
}
UPD:
This is not work too, i have standart sound
#Override
protected Notification getNotification(Context context, Intent intent) {
Notification n = super.getNotification(context, intent);
n.sound = Uri.parse("android.resource://" + context.getPackageName() + "beep1.mp3");
return n;
}
UPD:
I pu mp3 to folder res/raw/beep1.mp3 and use ("android.resource://" + context.getPackageName() + R.raw.beep1); but its not help
Assuming that you have your own subclass of ParsePushBroadcastReceiver and you declared it in Manifest, I recommend you to put your mp3 file in the /raw folder and to change your getNotification() method as follows
#Override
protected Notification getNotification(Context context, Intent intent) {
Notification n = super.getNotification(context, intent);
n.defaults = 2;
n.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.beep1);
return n;
}
If you want just to change sound the getNotification() method is the only one you need to overrid
Its work for me! Import: sound mus be here: res/raw/beep1.mp3 and path like this "android.resource://" + context.getPackageName() +"/"+ "R.raw.beep1"
#Override
public void onReceive(Context context, Intent intent) {
try {
JSONObject json = new JSONObject(intent.getExtras().getString(
"com.parse.Data"));
alert = json.getString("alert").toString();
} catch (JSONException e) {}
notifySound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.ic_launcher); //You can change your icon
mBuilder.setContentText(alert);
mBuilder.setContentTitle("Пользователь");
mBuilder.setSound(Uri.parse("android.resource://" + context.getPackageName() +"/"+ R.raw.beep1));
mBuilder.setAutoCancel(true);
resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, mBuilder.build());
}
}

Categories

Resources