Android OneTime IntentService dies when app is killed - android

I need to run a task after 10 seconds, even if the app is closed. I created IntentService:
class SomeService: IntentService() {
override fun onHandleIntent(intent: Intent?) {
Thread.sleep(10_000)
somefunction()
}
}
Intent service dies after app dies.
I can't relaunch it with BroadcastReceiver, because its one-time service, which must perform this action after 10 seconds

Quoting Android Developer Guide
IntentService is subject to all the background execution limits
imposed with Android 8.0 (API level 26)
You can read more about the restrictions here https://developer.android.com/about/versions/oreo/background
Some solutions you can try are
1)Have a foreground service (Attach a notification to the service)
In Java, the way I do is I have two utility methods created
public static void startNotificationAlongWithForegroundService(Service service,String CHANNEL_ID_FOREGROUND,String CHANNEL_NAME_FOREGROUND, String title, String body, Integer notification_id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(service, CHANNEL_ID_FOREGROUND)
.setContentTitle(title)
.setContentText(body)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher)
.setProgress(100, 0, true);
NotificationManager mNotificationManager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = mNotificationManager.getNotificationChannel(CHANNEL_ID_FOREGROUND);
if(channel==null) {
channel = new NotificationChannel(CHANNEL_ID_FOREGROUND,CHANNEL_NAME_FOREGROUND, NotificationManager.IMPORTANCE_NONE);
channel.setShowBadge(false);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(channel);
}
}
service.startForeground(notification_id, builder.build());
}
}
public static void destroyForegroundService(Service context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.stopForeground(true);
}
}
And in your service
#Override
protected void onHandleIntent(Intent intent) {
Utils.startNotificationAlongWithForegroundService(this,"channel_id","channelname","title","body",123);
//your work
Utils.destroyForegroundService(this);
}
2)Use JobService/Workmanager
I will update the answer with the examples on this shortly if you are not comfortable with using Job services/WorkManager.

Related

How to create a foreground service with notification for Android below Oreo 8.0?

I have created a foreground service using the following code which is in the override method OnStartCommand inside a service class called DemoIntentService.cs.
base.OnStartCommand(intent,flags,startId);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
Intent notificationIntent = new Intent(this, Java.Lang.Class.FromType(typeof(DemoIntentService)));
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
Notification.Builder notificationBuilder = new Notification.Builder(this, "Example_Service_Channel")
.SetSmallIcon(Resource.Drawable.AlertLightFrame)
.SetContentTitle(Resources.GetString(Resource.String.DialogAlertTitle))
.SetContentText(Resources.GetString(Resource.String.SelectTextMode))
.SetContentIntent(pendingIntent);
Notification notificationAfterBuild = notificationBuilder.Build();
StartForeground(123, notificationAfterBuild);
InitializeAlarmManager();
setAlarm();
}
return StartCommandResult.RedeliverIntent;
Obviously, the code above is only for Android Oreo 8.0 and above, the service works fine and the notification will not be cleared even though I close the app manually. (That's good, that's what I want !). However, when I use the above code to test on Android Nougat 7.1.1, it would not work.
Firstly, I have researched online they said there is no need to create a notification channel for Android below 8.0, so I remove the "Example_Service_Channel" which is the channelID. The app was deployed successfully, but the notification gone when I kill the app. Second thing, when I removed the channelID, Xamarin throw me a warning said "Notification.Builder.Builder(Context) is obsolete : deprecated" and the line has turn yellow. I ignore the error and deploy the app. The service did run as it is visible in the running service inside the developer options. But when I killed the app, the service and notification gone together. Is there any other way to create a foreground notification service that will never end for Android below 8.0? Thanks for any comment and idea.
i write a simple sample,and it works on Android 7.1. i just delete the Notification Channel from Android 8.0
1.Create a Service MyService.cs :
[Service(Enabled = true)]
public class MyService : Service
{
private Handler handler;
private Action runnable;
private bool isStarted;
private int DELAY_BETWEEN_LOG_MESSAGES = 5000;
private int NOTIFICATION_SERVICE_ID = 1001;
private int NOTIFICATION_AlARM_ID = 1002;
public override void OnCreate()
{
base.OnCreate();
handler = new Handler();
//here is what you want to do always, i just want to push a notification every 5 seconds here
runnable = new Action(() =>
{
if (isStarted)
{
DispatchNotificationThatAlarmIsGenerated("I'm running");
handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
}
});
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
if (isStarted)
{
// service is already started
}
else
{
DispatchNotificationThatServiceIsRunning();
handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
isStarted = true;
}
return StartCommandResult.Sticky;
}
public override void OnTaskRemoved(Intent rootIntent)
{
//base.OnTaskRemoved(rootIntent);
}
public override IBinder OnBind(Intent intent)
{
// Return null because this is a pure started service. A hybrid service would return a binder that would
// allow access to the GetFormattedStamp() method.
return null;
}
public override void OnDestroy()
{
// Stop the handler.
handler.RemoveCallbacks(runnable);
// Remove the notification from the status bar.
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Cancel(NOTIFICATION_SERVICE_ID);
isStarted = false;
base.OnDestroy();
}
//start a foreground notification to keep alive
private void DispatchNotificationThatServiceIsRunning()
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.SetDefaults((int)NotificationDefaults.All)
.SetSmallIcon(Resource.Drawable.Icon)
.SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
.SetSound(null)
.SetPriority(NotificationCompat.PriorityDefault)
.SetAutoCancel(false)
.SetContentTitle("Mobile")
.SetContentText("My service started")
.SetOngoing(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
StartForeground(NOTIFICATION_SERVICE_ID, builder.Build());
}
//every 5 seconds push a notificaition
private void DispatchNotificationThatAlarmIsGenerated(string message)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
Notification.Builder notificationBuilder = new Notification.Builder(this)
.SetSmallIcon(Resource.Drawable.Icon)
.SetContentTitle("Alarm")
.SetContentText(message)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(NOTIFICATION_AlARM_ID, notificationBuilder.Build());
}
}
2.in your activity :
protected override void OnResume()
{
base.OnResume();
StartMyRequestService();
}
public void StartMyRequestService()
{
var serviceToStart = new Intent(this, typeof(MyService));
StartService(serviceToStart);
}
try to start the service with
ContextCompat.startForegroundService(context,intent)
build the notification then call
startForeground(1, notification)
in onCreate() or onStartCommand() whatever works for you but after the service started and running don't forget to ask for permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Workmanager not working when app is in background

I'm trying to periodically run a service even when the app is killed or is in the background using workManager.
My RequestService class is given below:-
public class RequestService extends Worker {
public RequestService(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
displayNotification("MY Worker", "Background work Started");
Log.i("BackJob","Running");
return Result.SUCCESS;
}
private void displayNotification(String title, String task){
NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("MyApp","My Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), "My Notifications").
setContentTitle(title).setContentText(task)
.setSmallIcon(R.mipmap.ic_launcher);
notificationManager.notify(130, notification.build());
}}
This is the main activity code:-
final PeriodicWorkRequest WorkReq = new PeriodicWorkRequest.Builder(RequestService.class,15,TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(WorkReq);
The issue is if the app is killed or is in the background then workmanager stops working.
I'm testing this on a samsung device with android version pie.
P.S :- if the app is open then i see notifications continuously after 15 mins....however as soon as i close the app.....it stops working.....and there are no more notifications
You can use foreground Service for this , Foreground Service work when app is in background.
add this method in downork method
setForegroundAsync(createForegroundInfo(progress));
Override this method in workermanager class
#NonNull
private ForegroundInfo createForegroundInfo(#NonNull String progress) {
Context context = getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel("1", "channelName", NotificationManager.IMPORTANCE_NONE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
}
Notification notification = new NotificationCompat.Builder(context, "1")
.setContentTitle("title")
.setTicker("title")
.setSmallIcon(R.drawable.ic_launcher_background)
.setOngoing(true)
.build();
return new ForegroundInfo(1,notification);
}
Now you app will work in the background.
As Per the PeriodicWorkRequest.Builder official documentation available here
The intervalMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
This value is currently set to 900000 ms i.e, 15 minutes.
This is a working example that currently shows any notification regarding the version of the SO. But seemingly the problem can be related with the notify method from NotificationManagerCompat
private void makeStatusNotification(String message, Context context) {
String channelId = context.getString(R.string.worker_sync_notif_channel_id);
// Make a channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel, but only on API 26+
CharSequence name = context.getString(R.string.worker_sync_notif_channel_name);
String description = context.getString(R.string.worker_sync_notif_channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
// Add the channel
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
// Create the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_cloud_upload)
.setContentTitle(context.getString(R.string.worker_sync_notif_title))
.setContentText(context.getString(R.string.worker_sync_notif_subject))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(new long[0])
.setAutoCancel(true);
// Show the notification
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build());
}

startForegroundService() is throwing IllegalStateException in Oreo on app BOOT_COMPLETED

The application I am having (in Android O) will start a service after device reboot. Once the device is rebooted, in the onReceive() method of the broadcast receiver it is calling the service as startForegroundService() for Android OS 8 and above.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Inside the service class it is starting the notification from the onStartCommand() method.
But still it is throwing the IllegalStateException. Did someone faced similar issues in Android OS 8 and above?
You have to call startForeground() from the started service, it's in the docs:
Once the service has been created, the service must call its startForeground() method within five seconds.
Source
So for example you need to do this from your Service class:
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "channel_01";
String CHANNEL_NAME = "Channel Name";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setSound(null, null);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
Builder notification = new Builder(this, CHANNEL_ID).setSound(null).setVibrate(new long[]{0});
notification.setChannelId(CHANNEL_ID);
startForeground(1, notification.build());
}
}
The system allows apps to call Context.startForegroundService() even while the app is in the background. However, the app must call that service's startForeground() method within five seconds after the service is created.
Write your service's onCreate like below.
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
}
So that startForeground() can be called within 5 seconds of starting the service.

Foreground Service dont run constantly

In my app I use a foreground service that must run constantly. Sometimes the foreground service is stopped.
Under what circumstances can the OS kill my service (it happen even if there is enough memory, battery is full, phone is charging)?
This is what my code looks like until now:
public class ServiceTest extends Service {
public static Thread serverThread = null;
public Context context = this;
public ServiceTest(Context context) {
super();
this.context = context;
}
public ServiceTest() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (this.serverThread == null) {
this.serverThread = new Thread(new ThreadTest());
this.serverThread.start();
}
return START_STICKY;
}
private class ThreadTest implements Runnable {
#Override
public void run() {
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("Notification title")
.setContentText("Notification text")
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setSmallIcon(R.drawable.android)
.setOngoing(true).build();
startForeground(101, notification);
while(true){
//work to do
}
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
There is not a single... Many problems in your code... You may be getting it "0 Errors" as it is syntactically correct but it is androidicaly wrong, your basics are poor, reading of android documentation and implementation is very poor. Android never runs very poor things...
Problem : 1
Do you know for a service conventionally you should override onCreate, onStartCommand, onBind, onDestroy methods....?
I don't see onDestroy there....!!
Problem : 2
Do you know how to notify...? Your onStartCommand implementation is again making no sense.
KEEP IT EMPTY JUST RETURN START_STICKY
Problem : 3
How do you expect to run this under background execution limits...? Notify android first by making notification in oncreate only and with startforeground if needed...
I don't see it there.... you trying to do it in onstartcommand and again it is very poorly...
Well... take a look at working code below :
public class RunnerService extends Service
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
String NOTIFICATION_CHANNEL_ID = "1";
public RunnerService() { }
#Override
public void onCreate()
{
super.onCreate();
Log.d("RUNNER : ", "OnCreate... \n");
Bitmap IconLg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground);
mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this, null);
mBuilder.setContentTitle("My App")
.setContentText("Always running...")
.setTicker("Always running...")
.setSmallIcon(R.drawable.ic_menu_slideshow)
.setLargeIcon(IconLg)
.setPriority(Notification.PRIORITY_HIGH)
.setVibrate(new long[] {1000})
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setOngoing(true)
.setAutoCancel(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotifyManager.createNotificationChannel(notificationChannel);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
startForeground(1, mBuilder.build());
}
else
{
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotifyManager.notify(1, mBuilder.build());
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d("RUNNER : ", "\nPERFORMING....");
return START_STICKY;
}
#Override
public void onDestroy()
{
Log.d("RUNNER : ", "\nDestroyed....");
Log.d("RUNNER : ", "\nWill be created again automaticcaly....");
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent)
{
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("NOT_YET_IMPLEMENTED");
}
}
How to check....???
Remove the app from recents list and you should see in your logs the "Performing " message in logcat...
In what conditions it stops...?
It never stops ( until next boot..!! )... Yes it stops when user force stops application. And rarely if system finds it is having very low resources .... which is a very rare condition seems to occur as android has improved a lot over the time....
How to start it....?????
Wherever it may be from mainactivity or from receiver or from any class :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
context.startForegroundService(new Intent(context, RunnerService.class));
}
else
{
context.startService(new Intent(context, RunnerService.class));
}
How to check is service started or not....?
Simply Don't..... Even if you starts service how many times you wants.... If it is already running... then it won't be start again.... If not running then... will start it...!!
The criticism made in the chosen answer is not reasonable if the service needs an intent to work.
On higher version of Android, System will pause any foreground service while the device is locked, to minimize the power consumption even if it returns START_STICKY. So, to make a foreground task constantly, a wakelock is required.
Here's what android documentation describes wakeLock:
To avoid draining the battery, an Android device that is left idle quickly falls asleep. However, there are times when an application needs to wake up the screen or the CPU and keep it awake to complete some work.
To make a foreground service running constantly, acquire a wakeLock from inside the onCreate().
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyApp::MyWakelockTag");
wakeLock.acquire();
For further detail, have a look at official Android Documentation.

Periodic work requests using WorkManager not working

i am trying to write a periodic workmanager script but it just run when i open the app and it just run one time (not periodic) !
here is my main activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work);
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
NotifyWorker.pendingIntent = pendingIntent;
NotifyWorker.context = this;
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(NotifyWorker.class, 1, TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(periodicWorkRequest);
}
}
and this is my dowork method :
public Result doWork() {
Log.i("wd","wd");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context,"ctx")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.logo)
.setContentTitle("Title")
.setContentText("Desc")
.setContentIntent(pendingIntent);
android.app.NotificationManager notificationManager =
(android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 , notificationBuilder.build());
return Result.SUCCESS;
}
why its not run every 1 minute ? what i miss ?
Per the PeriodicWorkRequest.Builder documentation:
The intervalMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
That value is currently set to 900000 - i.e, 15 minutes.
First of all, you can disagree with my answer but here is the hack which I used in my project and this work very accurately without gives any problem.
It's time to see the code. One thing I pointed later and must read this point after the code. SECTION IMP
//this code in your activity, fragment or any other class
notify_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
OneTimeWorkRequest track_share_market = new OneTimeWorkRequest.Builder(NotificationWorker.class).setInitialDelay(1,TimeUnit.MINUTES).addTag("Stock_Market").build();
WorkManager.getInstance().enqueue(track_share_market);
Log.d("RishabhNotification","SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSs");
}
else {
Log.d("RishabhNotification","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
WorkManager.getInstance().cancelAllWorkByTag("Stock_Market");
}
}
});
Now your Worker class Code
public class NotificationWorker extends Worker {
public NotificationWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
try {
//Some heavy operation as you want there is no need to make another thread here
//track some website for weather changes or stock market changes
//In my case doWork takes only 10sec for executing this method
ShowNotification("Market Up","Gold Price goes upto ₹25,000 ","Check the app for the new update");
StartNewRequest();
return Result.success();
} catch (Exception e) {
e.printStackTrace();
StartNewRequest();
Log.d("RishabhNotification","ERERERERERERERERERERERERERERERERERERERERERERERERERERERE");
return Result.failure();
}
}
private void StartNewRequest()
{
OneTimeWorkRequest track_market = new OneTimeWorkRequest.Builder(NotificationWorker.class).setInitialDelay(1,TimeUnit.MINUTES).addTag("Stock_Market").build();
WorkManager.getInstance().enqueue(track_market);
}
private void ShowNotification(String Message, String name, String Information)
{
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Stock Market", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setSound(null,null );
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID);
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder.setAutoCancel(false)
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE|Notification.DEFAULT_LIGHTS)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(uri)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setPriority(Notification.PRIORITY_MAX)
.setContentTitle(Message)
.setContentText(name)
.setContentInfo(Information);
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
}
}
Now Read the SECTION IMP point
This Code perfectly working in Emulator, Pixel phone, Samsung phone, Moto phone, Asus Phone, One plus phone but this same code I tested in the Xioami Devices and Huawei devices they both devices not run the code for every specific time interval(They both run the code but time may be changed) which I define in my code. I don't know why is this happen on both devices. Maybe some optimization. Check this link for more https://www.reddit.com/r/androiddev/comments/9ra0iq/workmanager_reliability_for_periodic_tasks_on/
I have not tested this code in vivo and Oppo devices.

Categories

Resources