I am registering a broadcast receiver from a service. I need to show notification to user if location of device is off the code works fine but receiver does not create notification. I can see logcat messages on changing location status but notification is not created Please check the issue ! And is there any way to update the current notification of the service?
This is Service:
public class LockService extends Service {
BroadcastReceiver mReceiver;
Handler handler;
LocationManager locationManager;
#Override
public IBinder onBind(Intent intent) {
return null;
}
private static final int NOTIF_ID = 1;
#Override
public void onCreate() {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
mReceiver = new com.example.fizatanveerkhan.citycops.ScreenReceiver();
registerReceiver(mReceiver, filter);
super.onCreate();
}
private void startForeground() {
startForeground(NOTIF_ID, getMyActivityNotification(""));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.startForeground();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
Log.i("onDestroy Reciever", "Called");
}
super.onDestroy();
}
public class LocalBinder extends Binder {
LockService getService() {
return LockService.this;
}
}
private Notification getMyActivityNotification(String text) {
CharSequence title = "new";
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
}
return notification;
}
/* public void updateNotification() {
String text = "Some text that will update the notification";
Notification notification = getMyActivityNotification(text);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIF_ID, notification);
}*/
}
And this is broadcast receiver:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
private static final int POWER_OFF_TIMEOUT = 500;
private Handler handler = new Handler();
private Runnable powerOffCounterReset = new PowerOfTimeoutReset();
private int countPowerOff = 0;
private boolean screenOff;
//private LockService updateService = new LockService();
private final static String TAG = "LocationProviderChanged";
boolean isGpsEnabled;
boolean isNetworkEnabled;
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Log.i(TAG, "Location Providers changed");
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//Start your Activity if location was enabled:
if (isGpsEnabled || isNetworkEnabled) {
Log.i(TAG, "Location Providers on");
}
else {
Log.i(TAG, "Location Providers off");
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);
}
}
}
I can see logcat messages on changing location status but notification is not created
Changing notification code to this solved the problem
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "
com.example.fizatanveerkhan.citycops";
CharSequence name = "My Background Service";
String description = "My Background Service";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
NotificationManagerCompat notificationManagerq =
NotificationManagerCompat.from(context);
// notificationId is a unique int for each notification that you must define
notificationManagerq.notify(1, notificationBuilder.build());
}
So basically you need to create a foreground notification and update its contents on location change.
You can use the code below to create a foreground notification:-
//for foreground service notification
public Notification showForegroundNotification(String notificationTitle, String notificationBody, Intent intent, ServiceName serviceName) {
String id = mContext.getString(R.string.upload_notification_channel_id);
PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, id);
NotificationManager mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = mContext.getString(R.string.upload_notification_channel_name);
String description = mContext.getString(R.string.upload_notification_channel_description); //user visible
int importance = NotificationManager.IMPORTANCE_LOW;
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(false);
mChannel.enableVibration(false);
mChannel.setVibrationPattern(new long[]{0L});
mChannel.setSound(null, att);
if (mNotifyManager != null) {
mNotifyManager.createNotificationChannel(mChannel);
}
notificationBuilder
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVibrate(new long[]{0L})
.setSound(null)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setContentTitle(notificationTitle)
.setAutoCancel(true)
.setContentIntent(lowIntent);
} else {
notificationBuilder.setContentTitle(notificationTitle)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVibrate(new long[]{0L})
.setSound(null)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setAutoCancel(true)
.setContentIntent(lowIntent);
}
if (notificationBody != null) {
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody));
}
notificationBuilder.setContentText(notificationBody);
return notificationBuilder.build();
}
and you need to call startForegroundService();
private void startForegroundService(){
String dataTitle = SharedPrefer.getLastUpdatedLocationName();
String dataContent = SharedPrefer.getLastUpdatedLocation();
Intent intent = new Intent(WITHU.getAppContext(), MapLocateActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startForeground(121, showNotification.showForegroundNotification(dataTitle, dataContent, intent, ServiceName.SMART_LOCATION, -1, false));
}
So it will pass the updated location name and location which you can collect from SharedPreference or also can be called directly onLocationChanged.
Related
I'm new to developing an application. Currently, I'm working on push notification. Before this, I'm trying using Android 4.4, and the push notification work just fine. But, now I'm trying to debug on my Android 9 (Pie), but it seems like the notification does not appear.
I already try a few solutions. They suggest to use a notification channel for Android 8 and above. I have tried some of the solution from here: Previous question answer and here Previous question answer.
But, I don't know why it does not work for me.
Here is my code
public void onReceive(final Context context, final Intent intent) {
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
nm.createNotificationChannel(mChannel);
}
if (!intent.getExtras().getBoolean("cancel", false)) {
this.context = context;
prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
notification = new NotificationCompat.Builder(context, channelId);
count = intent.getExtras().getInt("count");
name = prefs.getString("name"+count, "");
hours = prefs.getInt("hora"+count, 8);
minutes = prefs.getInt("minuto"+count, 0);
minutesBefore = prefs.getInt("minutesBefore", 30);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH)
isScreenOn = pm.isInteractive();
else
isScreenOn = pm.isScreenOn();
if (!isScreenOn) {
#SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
wl.acquire(10000);
#SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
wl_cpu.acquire(10000);
}
/**
* notification
*/
final Intent notificationIntent = new Intent(context, Broadcast_TakenAction.class);
//Broadcast_TakenAction gets called when notification is clicked
notificationIntent.putExtra("count", count);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pIntent = PendingIntent.getBroadcast(context, count, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setAutoCancel(true);
notification.setLargeIcon(drawableToBitmap(ResourcesCompat.getDrawable(context.getResources(), R.drawable.notification_large_icon, null)));
notification.setSmallIcon(R.drawable.small_icon);
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle(name);
notification.setContentIntent(pIntent);
notification.setPriority(0);
notification.addAction(R.drawable.check, "Taken", pIntent);
if (intent.getExtras().getBoolean("shownBefore", false)) {
Runnable delayedThreadStartTask2 = new Runnable() {
#Override
public void run() {
new Thread(
new Runnable() {
#Override
public void run() {
for (int incr = 0; incr < minutesBefore; incr++) {
if (!intent.getExtras().getBoolean("cancel", false)) {
int time_left = minutesBefore - incr;
notification.setContentText(time_left + "m left.");
nm.notify(count, notification.build());
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException ignored) {
}
}
}
realNotification();
if (prefs.getBoolean("vibrates", true)) {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
}
}
}
).start();
}
};
delayedThreadStartTask2.run();
} else {
realNotification();
}
}
}
I'm not sure what wrong with my code. Please correct me if I'm wrong.
this code worked for me in any API number:
public void Notificate() {
try {
final String NOTIFICATION_CHANNEL_ID = "10001";
String notification_title = getResources().getString(R.string.label);
String notification_message =jsonArray.get(4).getAsString() ;
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ActivityMain.this)
.setSmallIcon(R.drawable.tahlil)
.setContentTitle(notification_title)
.setContentText(notification_message)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400})
.setSound(alarmSound);
Intent resultIntent = new Intent(getApplicationContext(), ActivityChatList.class);
resultIntent.putExtra("menuFragment", "favoritesMenuItem");
// resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getApplicationContext(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
if (mNotifyMgr != null) {
mNotifyMgr.createNotificationChannel(notificationChannel);
}
}
if (mNotifyMgr != null) {
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
} catch (Exception e) {
}
}
I created a foreground Service with persistent notification. I want to run this service 24x7. But my service is stopped/killed by the system approx 30-40 mins after killing the app. What can I do so that my service is not killed by the system. Its really important that service runs 24x7 to collect user data.
Thanks In Advance.
public class MyService extends Service {
String NOTIFICATION_CHANNEL_ID = "example.permanence";
final Restarter restarter = new Restarter();
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(getApplicationContext(), MyService.class));
} else {
startService(new Intent(getApplicationContext(), MyService.class));
}
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
Intent showTaskIntent = new Intent(getApplicationContext(), MainActivity.class);
showTaskIntent.setAction(Intent.ACTION_MAIN);
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager manager = (NotificationManager) getSystemService(NotificationManager.class);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(),NOTIFICATION_CHANNEL_ID);
notificationBuilder.setContentTitle("App is running in background");
notificationBuilder.setContentText("App is running in background");
notificationBuilder.setNumber(103);
notificationBuilder.setSmallIcon(R.drawable.icon);
notificationBuilder.setOngoing(true);
notificationBuilder.setPriority(5);
Notification notification = notificationBuilder.build();
NotificationManager notificationManger =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManger.notify(1, notification);
startForeground(2, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String channelName = "Background Service";
NotificationChannel chan = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName,
NotificationManager.IMPORTANCE_DEFAULT);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
chan.setLightColor(Color.BLUE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
}
NotificationManager manager = (NotificationManager) getSystemService(NotificationManager.class);
assert manager != null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
manager.createNotificationChannel(chan);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(),NOTIFICATION_CHANNEL_ID);
notificationBuilder.setContentTitle("App is running in background");
notificationBuilder.setContentText("App is running in background");
notificationBuilder.setNumber(108);
notificationBuilder.setSmallIcon(R.drawable.icon);
notificationBuilder.setOngoing(true);
notificationBuilder.setPriority(5);
Notification notification = notificationBuilder.build();
NotificationManager notificationManger =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManger.notify(1, notification);
try {
startForeground(3, notification);
}catch (Exception e) {
e.printStackTrace();
}
super.onStartCommand(intent, flags, startId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(getApplicationContext(), MyService.class));
} else {
startService(new Intent(getApplicationContext(), MyService.class));
}
registerReceiver(restarter,restarter.getFilter());
//work
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I have setup Notification Channels in Android Studio for sending my notifications.
So far, I can send a notification when I click a button.
However, I want to add a delay to when the notification is sent.. for example, send the notification after 20 seconds.
I know there is a function in the AlarmManager for System.getTimeInMillis, that would be related to this, but not sure where to go from here.
Here is my code:
public class MyNotificationPublisher extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#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");
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
}
public class EmailActivity extends AppCompatActivity {
private Button btnSend;
private NotificationManagerCompat notificationManager;
private long tenSeconds = 10000L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
notificationManager = NotificationManagerCompat.from(this);
btnSend = findViewById(R.id.button_send);
}
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
}
You can just schedule the notifications to be sent :-
Use the following method :
public void scheduleNotification(Context context, long delay, int notificationId)
{
//delay is after how much time(in millis) from current time you want to schedule the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(context.getString(R.string.title)) .setContentText(context.getString(R.string.content)) .setAutoCancel(true) .setSmallIcon(R.drawable.app_icon) .setLargeIcon(((BitmapDrawable) context.getResources().getDrawable(R.drawable.app_icon)).getBitmap()) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent intent = new Intent(context, YourActivity.class);
PendingIntent activity = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(activity); Notification notification = builder.build();
Intent notificationIntent = new Intent(context, MyNotificationPublisher.class);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, notificationId);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Then, the receiver class:
public class MyNotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
#Override
public void onReceive(final Context context, Intent intent)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int notificationId = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(notificationId, notification);
}
}
Then, call scheduleNotification with the appropriate arguments.
Use a handler to delay the execution of notification sending code
Update your code like that
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
notificationManager.notify(1, notification);
}
}, 20000);
}
I have a Firebase service that creates notifications on data messages.
It looks like
public class KaliumMessagingService extends FirebaseMessagingService {
private static final String TAG = KaliumMessagingService.class.getSimpleName();
private static final String NOTIFICATION_CHANNEL_ID = "natrium_notification_channel";
private final String NOTIF_GROUP_ID = "NATRIUM_NOTIF_GROUP";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData() != null && !MainActivity.appInForeground) {
sendNotification(remoteMessage);
}
}
#Override
public void onNewToken(String token) {
super.onNewToken(token);
SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(this);
sharedPreferencesUtil.setFcmToken(token);
}
public void initChannels(Context context) {
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Natrium transaction alerts");
notificationManager.createNotificationChannel(channel);
}
private void sendNotification(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String amount = data.get("amount");
if (amount == null) {
return;
}
initChannels(this);
try (Realm realm = Realm.getDefaultInstance()) {
Credentials c = realm.where(Credentials.class).findFirst();
// If not logged in, shouldn't post notifications
if (c == null) {
return;
}
}
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_status_bar);
builder.setContentText(getString(R.string.notification_body));
builder.setContentTitle(getString(R.string.notification_title, NumberUtil.getRawAsUsableString(amount)));
builder.setAutoCancel(true);
builder.setGroup(NOTIF_GROUP_ID);
builder.setSound(defaultSoundUri);
Notification pushNotification = builder.build();
nm.notify((int)System.currentTimeMillis(), pushNotification);
}
}
It works but, all the notifications are separate. I'd like them all to be grouped together/expandable. And clicking on it opens the main activity and dismisses all notifications.
I thought setGroup would achieve this behavior, but it hasn't seemed to make any difference.
Thanks
I ended up solving it as described in this blog post
https://blog.hopbucket.com/merge-firebase-notifications-9f96de7d026a
public class KaliumMessagingService extends FirebaseMessagingService {
private static final String TAG = KaliumMessagingService.class.getSimpleName();
private static final String NOTIFICATION_CHANNEL_ID = "natrium_notification_channel";
private int NOTIFICATION_ID = 1337;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(this);
if (remoteMessage.getData() != null && !MainActivity.appInForeground && sharedPreferencesUtil.getNotificationSetting() != NotificationOption.OFF) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
sendNotification(remoteMessage);
} else {
sendNotificationLegacy(remoteMessage);
}
}
}
#Override
public void onNewToken(String token) {
super.onNewToken(token);
SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(this);
sharedPreferencesUtil.setFcmToken(token);
}
public void initChannels(Context context) {
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Natrium transaction alerts");
notificationManager.createNotificationChannel(channel);
}
private void sendNotificationLegacy(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String amount = data.get("amount");
if (amount == null) {
return;
}
initChannels(this);
try (Realm realm = Realm.getDefaultInstance()) {
Credentials c = realm.where(Credentials.class).findFirst();
// If not logged in, shouldn't post notifications
if (c == null) {
return;
}
}
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_status_bar);
builder.setContentText(getString(R.string.notification_body));
builder.setContentTitle(getString(R.string.notification_title, NumberUtil.getRawAsUsableString(amount)));
builder.setAutoCancel(true);
builder.setGroup(TAG);
builder.setSound(defaultSoundUri);
Notification pushNotification = builder.build();
nm.notify((int)System.currentTimeMillis(), pushNotification);
}
#TargetApi(Build.VERSION_CODES.M)
private void sendNotification(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String amount = data.get("amount");
if (amount == null) {
return;
}
initChannels(this);
try (Realm realm = Realm.getDefaultInstance()) {
Credentials c = realm.where(Credentials.class).findFirst();
// If not logged in, shouldn't post notifications
if (c == null) {
return;
}
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
Intent onCancelNotificationReceiver = new Intent(this, CancelNotificationReceiver.class);
PendingIntent onCancelNotificationReceiverPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
onCancelNotificationReceiver, 0);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
StatusBarNotification[] notifications = manager.getActiveNotifications();
for (int i = 0; i < notifications.length; i++) {
if (notifications[i].getPackageName().equals(getApplicationContext().getPackageName())) {
Intent startNotificationActivity = new Intent(this, MainActivity.class);
startNotificationActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, startNotificationActivity,
PendingIntent.FLAG_ONE_SHOT);
Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_status_bar)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(getString(R.string.notification_title, NumberUtil.getRawAsUsableString(amount)))
.setContentText(getString(R.string.notification_body))
.setAutoCancel(true)
.setStyle(getStyleForNotification(getString(R.string.notification_body)))
.setGroupSummary(true)
.setGroup(TAG)
.setContentIntent(pendingIntent)
.setDeleteIntent(onCancelNotificationReceiverPendingIntent)
.build();
SharedPreferences sharedPreferences = getSharedPreferences("NotificationData", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(String.valueOf(new Random(NOTIFICATION_ID)), getString(R.string.notification_body));
editor.apply();
notificationManager.notify(NOTIFICATION_ID, notification);
return;
}
}
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Notification notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_status_bar)
.setContentTitle(getString(R.string.notification_title, NumberUtil.getRawAsUsableString(amount)))
.setContentText(getString(R.string.notification_body))
.setAutoCancel(true)
.setGroup(TAG)
.setContentIntent(pendingIntent)
.setDeleteIntent(onCancelNotificationReceiverPendingIntent)
.build();
SharedPreferences sharedPreferences = getSharedPreferences("NotificationData", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(String.valueOf(new Random(NOTIFICATION_ID)), getString(R.string.notification_body));
editor.apply();
notificationManager.notify(NOTIFICATION_ID, notificationBuilder);
}
private NotificationCompat.InboxStyle getStyleForNotification(String messageBody) {
NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle();
SharedPreferences sharedPref = getSharedPreferences("NotificationData", 0);
Map<String, String> notificationMessages = (Map<String, String>) sharedPref.getAll();
Map<String, String> myNewHashMap = new HashMap<>();
for (Map.Entry<String, String> entry : notificationMessages.entrySet()) {
myNewHashMap.put(entry.getKey(), entry.getValue());
}
inbox.addLine(messageBody);
for (Map.Entry<String, String> message : myNewHashMap.entrySet()) {
inbox.addLine(message.getValue());
}
inbox.setBigContentTitle(this.getResources().getString(R.string.app_name))
.setSummaryText(getString(R.string.notificaiton_header_suplement));
return inbox;
}
}
I have tried this code, but something happened unexpectedly. I can see a push message on my phone, but I can’t see the log in Android Studio. I think the method onMessageReceived isn’t working. Why did this happen?
My code follows.
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private boolean isVibrator = true;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
//vibrator();
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: "+remoteMessage.getNotification().getBody());
vibrator();
}
}
private void vibrator(){
if(isVibrator){
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {200,1000,150,1500,100,2000,50,3000};
vibe.vibrate(pattern, -1);
}
}
private void sendNotification(String messageBody) {
vibrator();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)//.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wakelock.acquire(5000);*/
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
Log.d(TAG, "send Server");
}
}