I want to run a background function which listens to the clipboard and when a string greater than 200 characters is copied then it will execute the function to show notification and then the proper Activity.class.
I am unable to create a service which runs in the background all the time even when the app is closed and the phone is restarted. Current I am starting that function in MyApp class which extends Application as I am unable to understand any tutorial based on services which can give me what I want.
Below is my code for MyApp
MyApp.class
public class MyApp extends Application {
private PrefManager prefManager;
#Override
public void onCreate() {
super.onCreate();
prefManager = new PrefManager(this);
if (prefManager.isNotifOns()) {
getClipTexts();
}
}
//Listener to listen change in clipboard
private void getClipTexts() {
final ClipboardManager clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
#Override
public void onPrimaryClipChanged() {
try {
String textToPaste = clipboardManager.getPrimaryClip().getItemAt(0).getText().toString();
if (textToPaste.length() > 200) {
makeNotification(textToPaste);
}
} catch (Exception ignored) {
}
}
});
}
//Creating notifications after copying the clipboard text
public void makeNotification(String input) {
Intent notifIntent = new Intent(getApplicationContext(), PostActivity.class);
notifIntent.putExtra("post", input);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Copy to Post";
int importance = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
importance = NotificationManager.IMPORTANCE_DEFAULT;
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Post copied content")
.setContentText(input)
.setAutoCancel(true);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
stackBuilder.addNextIntent(notifIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
}
Can anyone please write this function in a service which runs in background and supports in all Android Versions.
The above code does what I want as long as the app is running on foreground but I want to run the function even when App is closed or phone is restarted even in android versions above Android N. Please give me a proper answer I will be thankful for that.
Related
guys, I am developing an alarm app in which alarm is triggering good and at the right time but the drawback is when the alarm is ringing with an activity then when we press the home button too it is ringing the real problem is when the application is closed by pressing the home button and pressing or swiping close all apps the application getting destroyed I need something like Google does like showing a notification and playing sound even if the application is closed.
So I think someone is having Idea about this issue.
Here is what from Google Clock
Googel Clock image
Because of android Q, I had developed something that when the user is alive at the time of alarm then we just show notification with the help of this.
public class DismissAlarmNotificationController {
public final int NOTIFICATION_ID = 1;
public static final String INTENT_KEY_NOTIFICATION_ID = "notificationId";
public final String CHANNEL_ID = "channel-01";
private NotificationManager notificationManager;
private Context context;
private final int IMPORTANCE = NotificationManager.IMPORTANCE_HIGH;
public DismissAlarmNotificationController(Context context) {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
this.context = context;
}
public void showNotification() {
Intent fullScreenIntent = new Intent(context, DismissAlarmActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_ID, getChannelName(), IMPORTANCE);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_alarm_on_notification)
.setContentTitle(context.getString(R.string.dismiss_alarm_notification_title))
.setContentText(context.getString(R.string.dismiss_alarm_notification_body, getCurrentTime()))
.setAutoCancel(true)
.addAction(getDismissNotificationAction())
.setFullScreenIntent(fullScreenPendingIntent, true);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
public String getChannelName() {
return context.getString(R.string.app_name) + "Channel";
}
public void cancelNotification() {
notificationManager.cancelAll();
}
private NotificationCompat.Action getDismissNotificationAction() {
Intent dismissIntent = new Intent(context, DismissNotificationReceiver.class);
dismissIntent.putExtra(INTENT_KEY_NOTIFICATION_ID, NOTIFICATION_ID);
PendingIntent dismissNotificationPendingIntent = PendingIntent.getBroadcast(context, 0, dismissIntent, PendingIntent.FLAG_CANCEL_CURRENT);
return new NotificationCompat.Action.Builder(
0,
context.getString(R.string.dismiss_alarm_notification_dismiss_button_title),
dismissNotificationPendingIntent)
.build();
}
private String getCurrentTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Date currentTime = new Date();
return dateFormat.format(currentTime);
}
}
Thanks in advance.
Give a try to Android's WorkManager!
It lets you run background works even if the app is closed or the phone has been restarted.
Hope it will help!
How to show Foreground Service activity by clicking Notification? When I use my code, it starts new activity, but I need the activity, where service is working. Here is my code (Android Oreo):
public class APSService : Service
{
public static bool isRunning = false;
public override void OnCreate()
{
base.OnCreate();
}
public override void OnDestroy()
{
isRunning = false;
base.OnDestroy();
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
isRunning = true;
byte[] input = intent.GetByteArrayExtra("inputExtra");
Intent notificationIntent = new Intent(this, Java.Lang.Class.FromType((typeof(MainActivity))));
PendingIntent pendingIntent = PendingIntent.GetActivity(this,
0, notificationIntent, 0);
var builder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
.SetContentTitle("APS Service")
.SetSmallIcon(Resource.Drawable.notifypump)
.SetContentText("Start program...")
.SetContentIntent(pendingIntent);
Notification notification = builder.Build();
StartForeground(1, notification);
//do heavy work on background thread
return StartCommandResult.NotSticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
}
And in MainActivity in OnCreate:
protected override void OnCreate(Bundle savedInstanceState)
{
if (!APSService.isRunning)
{
createNotificationChannel();
startService();
}
else
{
NotificationChannel serviceChannel = new NotificationChannel
(
CHANNEL_ID,
"APS service Channel",
NotificationImportance.Default
);
notificationManager = (NotificationManager)GetSystemService(Java.Lang.Class.FromType((typeof(NotificationManager))));
notificationManager.CreateNotificationChannel(serviceChannel);
UpdateNotification("Loading...");
APSService.isRunning = true;
}
}
I hope you would help for solving this problem. Thanks a lot.
I write a demo about it, here is a GIF.
You can achieve the festure like following code.
[Service]
class MyForegroundService : Service
{
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
CreateNotificationChannel();
string messageBody = "service starting";
// / Create an Intent for the activity you want to start
Intent resultIntent = new Intent(this,typeof(Activity1));
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
stackBuilder.AddNextIntentWithParentStack(resultIntent);
// Get the PendingIntent containing the entire back stack
PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
var notification = new Notification.Builder(this, "10111")
.SetContentIntent(resultPendingIntent)
.SetContentTitle("Foreground")
.SetContentText(messageBody)
.SetSmallIcon(Resource.Drawable.main)
.SetOngoing(true)
.Build();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
//do you work
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
Here is my demo.
https://github.com/851265601/ForegroundServiceDemo
It's not clear to me what Activity you want to open
How to show Foreground Service activity
A Foreground service runs independently from your app
You are launching the MainActivity here:
Intent notificationIntent = new Intent(this,Java.Lang.Class.FromType((typeof(MainActivity))));
can you clarify what do want to do here?
ps: I know it's not an answer, can't comment yet
I am running a foreground service via broadcast receiver on boot completed.
It starts the services as desired and take only a a fraction of the device memory use and when I launch the app it increased the device memory usage as it should but when I close the app it still takes too much of memory even though the app has been closed and only the foreground service is running. What I want is really that it should use the same amount of memory after app has been closed as of it was using before the app was opened.
So, I did some digging through Android Profiler and what I found is that when foreground service starts after the boot it only opens Application.class, BroadcastReceiver.class, Service.class and few other background classes. And as I open the app it opens all the above classes and other activities . But when I close the app it still uses the device memory for graphic supports. I don't know how to stop that memory usage after the app has been closed.
Here are some screenshots of my Android Profiler
Before Launching the App through Foreground Notification Memory used 65MB
remember the foreground notification was started from the broadcast receiver after boot complete.
After Launching the app from Notifications Memory used 146 MB
While surfing through activities Memory used 165 MB
After app has been closed Memory used 140 MB
Now I want to know how to achieve the task of using the previous amount of memory use that was 65MB?
Here are my BroadcastReceiver and Service.class code.
Broadcast Receiver
public class BootCompletedIntentListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
Intent serviceIntent = new Intent(context,ClipMonitorService.class);
ContextCompat.startForegroundService(context,serviceIntent);
}
}
}
Service
public class ClipMonitorService extends Service {
private static final String TAG = "ClipboardManager";
private ExecutorService mThreadPool = Executors.newSingleThreadExecutor();
private ClipboardManager mClipboardManager;
private PrefManager prefManager;
#Override
public void onCreate() {
super.onCreate();
prefManager = new PrefManager(this);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mClipboardManager != null) {
mClipboardManager.removePrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Intent settingIntent = new Intent(this, SettingActivity.class);
PendingIntent pendingSettIntent = PendingIntent.getActivity(this, 0, settingIntent, 0);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
remoteViews.setOnClickPendingIntent(R.id.btn_action, pendingSettIntent);
remoteViews.setTextViewText(R.id.notif_subtitle, "1 Clips copied Today");
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContent(remoteViews)
.setVisibility(Notification.VISIBILITY_SECRET)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setContentIntent(pendingIntent)
.setColor(getResources().getColor(R.color.colorPrimary))
.setShowWhen(false)
.build();
startForeground(1, notification);
mClipboardManager =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
return START_STICKY;
}
private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener =
new ClipboardManager.OnPrimaryClipChangedListener() {
#Override
public void onPrimaryClipChanged() {
Log.d(TAG, "onPrimaryClipChangeds");
try {
String textToPaste = mClipboardManager.getPrimaryClip().getItemAt(0).getText().toString();
if (textToPaste.length() > 200) {
if (prefManager.isClipNotifOns()) {
mThreadPool.execute(new MakeNotifRunnable(
textToPaste));
}
}
} catch (Exception ignored) {
}
}
};
private class MakeNotifRunnable implements Runnable {
private final CharSequence mTextToWrite;
public MakeNotifRunnable(CharSequence text) {
mTextToWrite = text;
}
#Override
public void run() {
Intent notifIntent = new Intent(getApplicationContext(), PostNewsActivity.class);
notifIntent.putExtra("post", mTextToWrite);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 2;
String channelId = "channel1";
String channelName = "Clipboard Monitor Notification";
int importance = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
importance = NotificationManager.IMPORTANCE_DEFAULT;
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("Verify copied content")
.setContentText(mTextToWrite)
.setAutoCancel(true)
.setOnlyAlertOnce(true);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
stackBuilder.addNextIntent(notifIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
}
}
Help me to reduce memory usage
I'll be thankful for your answer.
P.S: As I am new to android development I may have uploaded too much information with jargons .Pardon me for that.
I'm new to Android programming and I'm trying to build my first app. Right now I want to send local notifications. Unfortunately I cannot receive notifications on devices running API 28 and above. I know there is a change in the way notifications are sent since Oreo and I have included code that creates the channel. It seems like if I run the app on a simulator with a lower API (e.g. 19) the notification is received. Also if I copy my code into a new project I receive the notifications, even on a simulator running Android Oreo. What settings in the project could cause notifications not to be received on Android Oreo? (There are no errors in Logcat)
My code for sending the notifications:
public static final String CHANNEL_1_ID = "channel1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannels();
}
public void setNotif(View view) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("hey")
.setContentText("world")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, notification);
}
private void createNotificationChannels() {
// if higher than android oreo
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);
}
}
The setNotif method is called by a tap of a button. Again, I'm new to Android programming so any advice would be helpful. Maybe even a different way in which I could diagnose the issue. Thank you!
Add this check in your setNotif() method:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
notificationManager.createNotificationChannel(getNotificationChannel(context));
setNotif() method will be changed like this :
public void setNotif(View view) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("hey")
.setContentText("world")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) notificationManager.createNotificationChannel(getNotificationChannel(context));
notificationManager.notify(1, notification);
}
And getNotificationChannel() method will look like this:
private static NotificationChannel getNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
return null;
CharSequence name = context.getString(R.string.app_name);// The user-visible name of the channel.
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(BuildConfig.APPLICATION_ID, name, importance);
notificationChannel.setShowBadge(true);
return notificationChannel;
}
I have a service which runs in foreground with, among other things, a stopwatch. When the service starts the notification appears, and when it ends I update it with sound and some text that indicates that it's finished. The problem is that this works well until api 25, but for 26 and 27 it updates the notification alright, but makes no sound. Here's the relevant code:
The creation of the notification inside the service:
mBuilder = new NotificationCompat.Builder(context, "Main")
.setSmallIcon(R.drawable.ic_notification_temp)
.setContentTitle(step.getDescription())
.setContentText(getString(R.string.notification_text))
.setVisibility(VISIBILITY_PUBLIC)
.setOngoing(true);
.setDeleteIntent(deletePendingIntent);
.setContentIntent(contentPendingIntent);
.addAction(R.drawable.ic_stop_red_24dp, getString(R.string.cancel),finnishPendingIntent);
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
The update to the notification builder when the "work" is finished:
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setVibrate(new long[]{0, 300, 0, 400, 0, 500});
mBuilder.setOngoing(false);
mBuilder.setAutoCancel(true);
mBuilder.setContentText(getString(R.string.notification_finished_text));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setChannelId("Sound");
mBuilder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
mNotificationManager.notify(mId, mBuilder.build());
The 2 channels created just for api 26 or up on app start:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the normal NotificationChannel
CharSequence name = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel("Main", name, importance);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
// Create theNotificationChannel with sound
importance = NotificationManager.IMPORTANCE_HIGH;
name = getString(R.string.notification_channel_sound);
NotificationChannel sound = new NotificationChannel("Sound", name, importance);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
notificationManager.createNotificationChannel(sound);
}
And that's where I'm at now. I've tried to not use setsound() as I've read that the notification should just play the default sound with the appropriate importance (and of course I've even uninstalled the app between tries to correctly update the channel settings) but nothing seems to work for api 26 and I just don't know what I'm doing wrong.
I had the exact same problems with most of my emulator AVDs. The following fixed it for me:
start the affected AVD
long press the AVD's power button
restart the AVD
Afterwards it should work again.
Tried to reproduce your issue and finished with created MVP, maybe this will help you to find the problem:
Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View btn = findViewById(R.id.clickMe);
btn.setTag(NotifService.CHANNEL_ID_MAIN);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String channelId = (String) v.getTag();
Intent intent = new Intent(v.getContext(), NotifService.class);
intent.putExtra(NotifService.TAG, channelId);
if (channelId.equals(NotifService.CHANNEL_ID_MAIN)) {
v.setTag(NotifService.CHANNEL_ID_SOUND);
} else {
v.setTag(NotifService.CHANNEL_ID_MAIN);
}
v.getContext().startService(intent);
}
});
}
}
Service:
public class NotifService extends IntentService {
public static final String TAG = "NotificationService";
public static final String CHANNEL_ID_MAIN = "Main";
public static final String CHANNEL_ID_SOUND = "Sound";
public static final int NOTIFICATION_ID = 123;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public NotifService() {
super(TAG);//Used to name the worker thread, important only for debugging.
}
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID_MAIN, "Channel Main", NotificationManager.IMPORTANCE_LOW);
NotificationChannel sound = new NotificationChannel(CHANNEL_ID_SOUND, "Channel Sound", NotificationManager.IMPORTANCE_HIGH);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
notificationManager.createNotificationChannel(sound);
}
}
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
String channelId = intent.getStringExtra(TAG);
showNotification(channelId);
}
private void showNotification(String channelId) {
boolean inProgress = channelId.equals(CHANNEL_ID_MAIN);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Work")
.setContentText(inProgress ? "InProgress" : "Finished")
.setOngoing(inProgress)
.setVisibility(VISIBILITY_PUBLIC)
.setAutoCancel(!inProgress);
if (!inProgress) {
builder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
}
This works good on my device 8.1 and Emulator 8.1 (without sound on first click for first notification and with vibration + sound on second click for work complete notification).