How to Realize an Update Service is Running in the Background? - java

I'm currently working on an app for the Android OS that displays some data. To ensure this data is up-to-date, it is required that the app fetches updates from a remote server from time to time.
As the data does not change very often, this update should be carried out once per week. I want to give the user the ability to choose the weekday and daytime of the update (and optionally disable this feature completely).
The thing is: this update should be carried out even when the user is not using the phone at this moment, even when the phone is currently sleeping and even when the phone has been rebooted recently and the app hasn't been started yet.
The first thing I thought of was a remote service that starts at system boot, determines the time when to run the update, sets a timer and then waits/sleeps for the timer to fire.
Now, I was told I should rather use alarm timers or some kind of handlers... the more I read about this topic, the more ways to do this seem to exist.
Now, I'm a bit lost which method is the best for me... so here is what I need:
I want to execute some code at a time that is specified.
This timer is used to trigger the execution of code 7 days in the future. (i.e., every week at a given weekday and time)
The code should run WITHOUT waking the phone up if it is "sleeping" (screen dimmed).
When running the code, no activity should be started. i.e. no app pops up on the screen.
The code that is executed should fetch some data from the internet. If at this time no internet connection is available, the timer should be set to sleep 30 minutes and then try again.
After completing the code execution, the timer will be set for the next interval, which will be 7 days later.
The timer should be started at system boot, e.g., if I reboot the phone, the timer should determine the next date to execute the code and schedule the timer. This has to work without ANY user interaction! (i.e. without the app being started itself)
When "sleeping", the thread/service/timer/whatsoever should not consume any system resources if possible...
What i need is pretty much a simple unix cronjob.
I think anyone here knows "newsrob" for android? What I want to realize is pretty much the same as the newsrob-updateservice.

Android Service + Broadcast Receiver + Alarm Service will solve your purpose -
Your service will be invoked from BroadCast Receiver and In Broadcast receiver you should register for various events - BOOT_RECEIVER , ACTION_USER_PRESENT , which will take care of your ALARM reset and update task.
Thanks.

Related

Deleting abandoned firestore documents, by keeping a timer running after the app is killed

I'm working on an app where the user creates a party where people can join, and all parties are stored in a Firestore collection as documents.
What I want to do is that when the user leaves the app after creating a party, he gets 5m, after 5m the party he created gets deleted from the cloud firestore.
So basically, I want to remove the inactive firestore documents(parties) as soon as possible.
I tried to make a timer, when he doesn't kill the app, the timer works well and deletes the document after 5m.
The problem is that when he kills the app, the app obviously stops, so does the timer, which prevents me from deleting his party. What should I do? Is there a way to make the timer keeps ticking even after killing the app?
The timer is just a solution I thought of to delete the abandoned parties, other suggestions are welcomed.
I tried to make an explicit broadcast which is triggered in onStop, and I start the timer in onRecieve, but onRecieve stops when the app is killed, to make it run when the app is killed I need to trigger it after the app is killed, but I don't know how to do this.
Note: Solutions other than cloud functions are preferable. But if there is no other way please inform me.
You can do this by using a WorkManager, you follow the steps below for implementing it.
Create a WorkManager and extend it with CoroutineWorker instead of a Worker.
Write the code for deleting the parties in the doWork() function of that Work Manager.
Create a one time Work Request using OneTimeWorkRequestBuilder with that Work Manager.
Finally, you need to submit your WorkRequest to WorkManager using the enqueue() method at the time when you are starting that timer.
Don't forget to setInitialDelay() which will be like a timer for the Work Manager. After implementing this, you can also remove the timer from the app.
This method will work in both conditions when the app is background or foreground.
For example, you can also check: https://developer.android.com/topic/libraries/architecture/workmanager/basics

Is it possible to run a daily task on android without openning the app?

I want to create an app that daily notifies me a value on a web page, I found this answer. It says that JobScheduler will do the trick for the daily part but I am not sure if it is going to run when the app is closed.
By the way I found that if I want to run a job every 3 seconds the code will be the following:
JobInfo.Builder builder = new JobInfo.Builder(1,
new ComponentName(getPackageName(),
JobSchedulerService.class.getName()));
builder.setPeriodic(3000);
If it is daily, should the time be:
builder.setPeriodic(86400000);
Or is there any way to Schedule at a exact time e.g. 9:00 a.m.
Unless your app has been force closed, any job scheduled with job scheduler will run even if the app is terminated. If needed it will be restarted. The only thing that will prevent it is if you declare the job not persistent and reboot the device.
Try to use AlarmManager. You can find example here.

What is the correct way to use repeating alarms for short intervals in Android 5.0+?

So I need to send coordinates from my current location to a server, in very short frequences (30 seconds). Right now I am doing it with AlarmManager setRepeating(), but Android 5.0+ allows intervals from up to 1 minute to save battery.
My question would be:
Is my way really efficient? I need to run this repeating alarm in the background, even when the device is off. Currently I am executing pendingintent which leads to a broadcastreceiver which in turn executes to asynctasks, one for server authentication, one for posting the coordinates.
Is my way really efficient?
No. This is why it is not supported out of the box on Android 5.1+, and this is why Android 6.0 introduced Doze mode.
I need to run this repeating alarm in the background, even when the device is off.
I assume that by "the device is off" that you really mean "the screen is off". If the device is powered down, your code will not run.
You can use setExact() to "manually" do your own repeating events on a 30-second interval, where the work that you do on the alarm event includes scheduling the next alarm. This too will fail on Android 6.0+ devices, when the device is in Doze mode. The only way to get every-30-second behavior on Android 6.0+ would be for the user to add your app to the battery optimization whitelist in Settings.
Currently I am executing the pendingintent which leads to a broadcastreceiver which in turn executes to asynctasks, one for server authentification, one for posting the coordinates.
First, that is unlikely to be reliable. Your process can be terminated as soon as onReceive() returns, since Android thinks that your work is done.
Second, AsyncTask is usually pointless from a background operation like a broadcast. The entire point behind AsyncTask is for you to do work on the main application thread when background work ends, and there is little reason to do work on the main application thread in the background. For this and the above reason, use a single IntentService to replace the two AsyncTasks.
Third, there is a decent chance that, on any given alarm event, you will be unable to complete your work in 30 seconds, due to network congestion, server issues, etc. You need to make sure that you handle this appropriately, so that you do not wind up queueing up all sorts of requests (or, in your current implementation, fork lots of parallel AsyncTasks all trying to do their work).

Run background code all the time when Android device is up

I want to run some code (mainly record system logs) in the background every certain time. This code runs all time when device is up. I have an app to control the start and stop of this recording code. I have tried putting the recording code in the service, but I found that the service always stops when app exits. This is not what I want. This function needs no notification.
BTW, this function is only for my custom Android system. So I have enough privileges such like system, driver or root. But I still want a way that is "high“ enough and affects the system least. So some normal java code is best, the kernel c/c++ modification to the custom OS is my last choice.
Thx.
Make a service class and give the permission to the maniefest
Here is the example...
https://developer.android.com/training/run-background-service/create-service.html
and do your stuff in the service, you can set time interval for that.

Pushing or Pulling notifications

We want to implement a back end server [Java EE] for mobile application that sends notification to mobile on some events, I'm asking about the best/simplest approach whether Pushing or Pulling notifications, here you are my ideas/questions
1- The requirement is to send instantly the notifications to the mobile as long as the application is running no need to send if it's not running
2- I read that to push notifications to IOS or Android, I will need to connect to apple/google notifications servers, I felt that this is complicated especially that it requires low level socket programming, but based on number 1 and the project has limited time and budget, do we really need pushing ? and is it really complex
3- I read that pulling date may drain battery and consume data, but what if implementing a simple job on the mobile that runs only 3 or 4 times a day, invoking a simple web service on back end server asking for the notifications
P.S will be much appreciated if you can provide some tutorials for similar cases :)
1) If you're application is already running, is it connecting to the same location anyways? If so you might as well pull for the notifications at that point. However, if the app isn't actively connecting, i would attempt to avoid pulling.
2) Interacting with Notification servers on google and apple site directly, can indeed be a cumbersome task. However there are companies that have made this much easier for you. The advantage of using companies like urbanairship, xtify and mblox will get you started with sending push messages in minutes. (for an example take a look at http://developer.mblox.com/docs/ in the tutorial section).
3) depending on the data you try to present, end users now a days are used to instant data. I can't imagine a service whereby pulling 3 to 4 times a day is sufficient, however if your use case is truly limited to 4 times a day, and there is no other activity going on in the background process you create for this, you might as well have the background process running. But do think this through carefully... If at any point in time you want to increase the number of times a day you read, you might soon get to the point where a rewrite is needed to ensure end user satisfaction.

Categories