I'm using OneSignal Notification service to send a notification. As per documentation, I'm doing setup it worked well before for lower Android SDK. After migrating to androidX it's showing incompatible types for NotificationCompat. I didn't find a proper solution to this problem. Please comment on your answer. Find the Code below
MyNotificationExtenderService.java
package ak.wp.meto.notification;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import com.onesignal.NotificationExtenderService;
import com.onesignal.OSNotificationDisplayedResult;
import com.onesignal.OSNotificationReceivedResult;
import java.math.BigInteger;
public class MyNotificationExtenderService extends NotificationExtenderService {
#Override
protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
// Read Properties from result
OverrideSettings overrideSettings = new OverrideSettings();
overrideSettings.extender = new NotificationCompat.Extender() {
#Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
// Sets the background notification color to Red on Android 5.0+ devices.
return builder.setColor(new BigInteger("FFFF0000", 16).intValue());
}
};
OSNotificationDisplayedResult displayedResult = displayNotification(overrideSettings);
Log.d("OneSignalExample", "Notification displayed with id: " + displayedResult.androidNotificationId);
return true;
}
}
BINGO!!! I modified my code in this way
MyNotificationExtenderService.java
package ak.wp.meto.notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.net.Uri;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import com.onesignal.NotificationExtenderService;
import com.onesignal.OSNotificationReceivedResult;
import ak.wp.meto.R;
import ak.wp.meto.activity.MainActivity;
import ak.wp.meto.activity.PostDetailsActivity;
import ak.wp.meto.data.constant.AppConstant;
public class MyNotificationExtenderService extends NotificationExtenderService {
#Override
protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000})
.setSound(defaultSoundUri);
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
return false;
}
}
This worked for me
Related
Hey I am just learning to Android development so I am trying to make push notifications. Book I read says to build it like that. But android studio says "Builder is deprecated" about NotificationCompat.Builder(this)
I also tried to find information on the internet, but none of it works.
This is my code:
package com.example.notifications;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
public static final int NOTIFICATION_ID = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view){
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentText("bioba")
.setContentTitle("aboba");
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
I use emulator of Android 8.1
Use public Builder(#NonNull Context context, #NonNull String channelId) instead, where channelId is the NotificationChannel where the constructed Notification will be posted.
Is there a way to make android notification stay on screen for over 4 seconds.
For example:
Phone App has notification for incoming call, when this notification shows up (Incoming call) it does not leave the screen until the user is interacting with the notification (Accept call / deny call / go to phone app). However I have not seen a way to make notification last on screen (foreground) for over 4 seconds. Even when i am setting the FLAG_INSISTENT and FLAG_NO_CLEAR the notification last visible on screen for 4 - 5 seconds...
FLAG_INSISTENT - keeps beeping and vibrate on high priority notification but still the notification is going off the screen after 4 seconds and the user need to drag bar down in order to "see" the notification.
I am looking for a way to put a notification the same way that the phone app is doing it meaning keep the notification ON SCREEN until the user interacts with it.
Here is an example of main activity:
My MainActivity.java:
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private NotificationManagerCompat notificationManager;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationManager = NotificationManagerCompat.from(this);
Intent YesReceive = new Intent(this, com.eddieharari.notifi.Data.class);
YesReceive.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntentYes = PendingIntent.getActivity(this,12345, YesReceive,
0);
Notification notification = new NotificationCompat.Builder(this, App.CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("My Notify TITLE")
.setContentText("This is my notification Message")
.setPriority(NotificationManagerCompat.IMPORTANCE_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setOngoing(false)
.setAutoCancel(true)
.setContentIntent(pendingIntentYes)
.setPriority(Notification.PRIORITY_MAX)
.build();
notification.flags = notification.flags | Notification.FLAG_INSISTENT | Notification.FLAG_NO_CLEAR;
notificationManager.notify(1, notification);
}
}
My App.java (where i set Notification Channel)
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String CHANNEL_1_ID = "channel1";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("This is channel 1");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
}
I FOUND OUT THE FOLLOWING:
Fullscreen intent inside the notification with high priority = true (second argument for the intent) leaves the notification on top of the screen till user interaction !
When using FullScreen intents don't forget to ask for fullScreenIntent permissions within the manifest....
When I install the app directly from android studio onto my phone per usb everything works well. I am working with push notifications that work with this method. But when I export my app in android studio and get the apk file and then install it per this apk file onto my phone everything works but not the notification??
Do you understand what I mean?
I can play my app per android studio directly onto my phone and it works 100% well ( I also get the expected push notifications).
After the export I get an apk file. I install this apk file manually and I get my app which looks great at first, only the notifications dont come although they come when I install it per android studio directly.
What am I doing wrong? Isnt the apk file the right file? Maybe I need another file? The code must be good because everything is fine when pushing play in android studio.
EDIT: Here is my code for the notifications:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.util.Random;
public class NotificationHelper extends ContextWrapper {
private static final String TAG = "NotificationHelper";
public NotificationHelper(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannels();
}
}
private String CHANNEL_NAME = "High priority channel";
private String CHANNEL_ID = "com.example.notifications" + CHANNEL_NAME;
#RequiresApi(api = Build.VERSION_CODES.O)
private void createChannels() {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("this is the description of the channel.");
notificationChannel.setLightColor(Color.RED);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
}
public void sendHighPriorityNotification(String title, String body, Class activityName) {
Intent intent = new Intent(this, activityName);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 267, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
// .setContentTitle(title)
// .setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setStyle(new NotificationCompat.BigTextStyle().setSummaryText("summary").setBigContentTitle(title).bigText(body))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
NotificationManagerCompat.from(this).notify(new Random().nextInt(), notification);
}
}
And here is my code where I call the notification:
package com.example.geofencing1;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import com.google.android.gms.maps.model.LatLng;
import java.util.List;
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "GeofenceBroadcastReceiv";
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// Toast.makeText(context, "Geofence triggered...", Toast.LENGTH_SHORT).show();
NotificationHelper notificationHelper = new NotificationHelper(context);
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()){
Log.d(TAG, "onReceive: Error receiving geofence event...");
return;
}
List<Geofence> geofenceList = geofencingEvent.getTriggeringGeofences();
for (Geofence geofence: geofenceList) {
Log.d(TAG, "onReceive: " + geofence.getRequestId());
}
// Location location = geofencingEvent.getTriggeringLocation();
int transitionType = geofencingEvent.getGeofenceTransition();
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
Toast.makeText(context, "GEOFENCE_TRANSITION_ENTER", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_ENTER", "", MapsActivity.class);
break;
case Geofence.GEOFENCE_TRANSITION_DWELL:
Toast.makeText(context, "GEOFENCE_TRANSITION_DWELL", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_DWELL", "", MapsActivity.class);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
Toast.makeText(context, "GEOFENCE_TRANSITION_EXIT", Toast.LENGTH_SHORT).show();
notificationHelper.sendHighPriorityNotification("GEOFENCE_TRANSITION_EXIT", "", MapsActivity.class);
break;
}
}
}
First of all I would like to thank you for clicking on this thread.
Thank you so much for taking your time to read this.
I was planning for the application push a notification on a specific time.
I followed some tutorials online but it seems it doesn't work.
There is no error message on the code itself but no notification is coming out.
Here's my "Notification_receiver.java" file:
package com.example.reviewerapplication;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
public class Notification_receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context,Chapterchoice.class);
String daily10 = "daily";
intent.putExtra("daily",daily10);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Sample Title")
.setContentText("same message")
.setAutoCancel(true);
if (intent.getAction().equals("MY_NOTIFICATION_MESSAGE")) {
notificationManager.notify(100, builder.build());
}
}
}
This is what is on my MainActivity:
//Daily Notification
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY,21)
calendar.set(Calendar.MINUTE,53)
calendar.set(Calendar.SECOND,0)
val intent2 = Intent(this, Notification_receiver::class.java)
intent2.setAction("MY_NOTIFICATION_MESSAGE")
var pendingIntent = PendingIntent.getBroadcast(this,100,intent2,PendingIntent.FLAG_UPDATE_CURRENT )
var alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.timeInMillis,AlarmManager.INTERVAL_DAY,pendingIntent)
I actually got it fixed just now.
my issue is that I used "activity" in the Manifest instead of using "receiver"
I'm developing a chat application and I am using Firebase Cloud Messaging. Notification works properly. When the phone is locked, the notification is received properly, but the sound is not generated.
Any help is appreciated.
FCMMessagingservice.java
package com.synergywebdesigners.nima;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.WindowManager;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import static android.app.Notification.VISIBILITY_PUBLIC;
import static com.android.volley.VolleyLog.TAG;
/**
* Created by Ashish Shahi on 13-04-2017.
*/
public class FcmMessagingService extends FirebaseMessagingService {
long[] pattern = {500,500,500,500,500,500,500,500,500};
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
PowerManager pm = (PowerManager)getSystemService(
Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE,
TAG);
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
Intent intent = new Intent(this, Memberlist.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.mipmap.ic_action_title)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setDefaults(0)
.setLights(Color.RED, 500, 500)
.setPriority(Notification.PRIORITY_HIGH)
.setOngoing(true)
;
wl.acquire();
// ... do work...
wl.release();
/*notificationBuilder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
notificationBuilder.setVibrate(pattern);*/
notificationBuilder.setStyle(new NotificationCompat.InboxStyle());
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Go to FCM CONSOLE and enable sound and define key 'sound'==>'default';
and go to php cansole and and type Following code 'sound'==>'default'; thats work properly