File Cleaning Service - android

As a requirement in Android OS phone, I am developing an app which will clean up a particular folder in a specified interval of time, say every 30 minutes.
I can run a service and clean up the folder every 30 mins. I have few questions over this,
1.Service has onStartCommand, which will be executed when the service starts, can I call a function here which has a Handler which runs every 30 minutes? Example
public int onStartCommand(Intent intent, int flags, int startId){
cleanUpData();
return START_REDELIVER_INTENT;
}
public void cleanUpData()
{
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// call the function again
cleanUpData();
}
}, "30 mins");
}
This code iterates the cleanUpData every 30 mins.
a. Is this correct?
b. Will this hamper the performance?
c. Should I use a separate thread as mentioned in numerous tutorials?
d. Should I use a service after-all? Or is there any other method?
AlarmManager provides the scheduled repeated alarms, but this does not work when the phone is in sleep mode. I do not want to wake up the screen as it does not require any human interaction. Can I ignore AlarmManager? Or does AlarmManager has functionality to run the code even when the phone is in sleep mode and phone wake up is false?
Please suggest. Thanks in advance!

you should use a separate thread for cleaning up the folder.I will not suggest you to use handler inside a service as it runs in the same process as app so a long running operation can make it unresponsive,instead of this use intentservice as it runs on its own thread.
And for the device sleep problem fire an broadcast receiver and acquire custom wake up lock in this broadcast receiver and then invoke your service from here.

Related

Need to have one background task to run for every minute in android

In one of my android applications, I need to run a task for every minute. It should run even if the app closes and when device is in Idle state also.
I have tried handler, it is working fine when device is active, but not working when device is in idle state.
I have tried workmanager(one time and repeated ) as well. Document says this works even when the device is in Idle mode, but this is stops working after 3/4 repeats.Workmanager is inconsitent, its working sometimes and not working most of the cases till i reboot device.
Can anyone suggest better way to handle the situation?
Thanks
bhuvana
Work manager can only work within 15 minutes of interval, if you do not define a longer time. To run something every minute, you need a Foreground Service with a sticky notification in it. There is no other way to run something every minute.
To start a foreground service, create a service as usual, and in its onStartCommand, call startForeground and from the method, return START_STICKY. These should achieve what you need.
Edit: Sample code for handler thread (this is Java btw, should be similar on Xamarin):
private HandlerThread handlerThread;
private Handler backgroundHandler;
#Override
public int onStartCommand (params){
// Start the foreground service immediately.
startForeground((int) System.currentTimeMillis(), getNotification());
handlerThread = new HandlerThread("MyLocationThread");
handlerThread.setDaemon(true);
handlerThread.start();
handler = new Handler(handlerThread.getLooper())
// Every other call is up to you. You can update the location,
// do whatever you want after this part.
// Sample code (which should call handler.postDelayed()
// in the function as well to create the repetitive task.)
handler.postDelayed(() => myFuncToUpdateLocation(), 60000);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
handlerThread.quit();
}

Android, keep CPU on when display is turned off?

I'm at my wits end with this issue. Can't find a good solution for it! In my app I have a service within which a timer gets scheduled over and over. That means after each timerTask is executed, another is started (first, both the timer and timerTask are canceled and then are assigned a new Timer and TimerTask). This is done 24 hours a day! I need this: First launch the app, start the service, then turn off the display and leave the device alone. But trouble is every time I come back to the device, I find my app has finished some tasks then is stuck on a timer although its time interval is passed! I think this is because of CPU sleeping.
For more explanation, suppose I have a list of time intervals in seconds: {60,100,40,120,80}. I start the service and leave the device alone for 5 minutes. Then I come back and see that tasks at 60 and 100 secs are done. But the service is stuck at the task at 40!
Each task includes a very simple network job that takes 5 secs at most.
I tried a wakelock but It's not gonna help. I don't know why!
Here is a code of my service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(id, new Notification());
pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK,"");
wl.acquire();
doAction();
return START_STICKY;
}
private void doAction(){
if (timer != null)
timer.cancel;
if (timerTask != null)
timerTask.cancel;
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
doAction();
//Do some network job!
}
};
timer.schedule(timerTask, getNewInterval());
}
You shouldn't keep the wakelock and maybe some power managing system feature kills your service because of this. Read documentation for:
WakefulBroadcastReceiver
and
AlarmManager
and see if first option or second one combined for example with IntentService can't fulfill your requirements. You can reset your alarm when trigerred by AlarmManager to another moment in time, even precisely, using setExact()

"Application is not responding. Would you like to close it?" getting an error while running service in Android

I have an Android application that has a button that starts the service.
Here is the service:
public class SimpleService extends Service
{
#Override
public int onStartCommand(Intent intent,int flags, int startId)
{
Toast.makeText(this,"Service Started",Toast.LENGTH_SHORT).show();
Integer i=0;
while (i<10)
{
Log.d("Hi",i.toString());
SystemClock.sleep(5000);
i++;
}
Log.d("Hi","return START_STICKY");
return START_STICKY;
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this,"Service Stopped",Toast.LENGTH_SHORT).show();
}
}
When I clicked on the button, the service starts successfully, but after some while, in the emulator, I got an error like
Application is not responding. Would you like to close it?
Am I doing anything wrong in service implementation?
What I want to do is perform a task on every 5 seconds even if my application got killed.
I tried with IntentService but it got killed when my app got killed so my task remains incomplete.
while (i<10)
{
Log.d("Hi",i.toString());
SystemClock.sleep(5000);
i++;
}
I would like to point out this part of your code. Here what you are doing is once your service starts, you are doing 10 iterations of loop and in each iteration you are pausing execution for five seconds (which is a lot of time in terms of execution). As services run in the main process, in my opinion, they block the main thread, which means during the sleep, if your app is accessed, you will get the ANR (App not responding) error. Thus, these types of tasks should be run in a separate thread.
If you want to perform some repetitive tasks on the background, I'd suggest you make use of a AlarmManager component of the Android SDK.Alarm manager is a system service, thus you can access it by using the following line of code.
AlarmManager mAlarmMgr=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
//Then you can set alarm using mAlarmMgr.set().
You will then receive the alarm in a AlarmReceiver.
AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. inside onReceive() you can start an activity or service depending on your need like you can start an activity to vibrate phone or to ring the phone.
I hope this helps. Cheers!
Since By Default, all your app components (like Activity, Service etc) runs in Main/UI Thread, and if it get blocked, Android shows ANR dialog.
Also, Each of lifecycle method of service is called from UI thread. If you need background task to be running all the time, you can crate new thread for this.
You may try below code inside your Service class:
new Thread(new Runnable(){
public void run() {
while(i<10)
{
Thread.sleep(5000)
//REST OF CODE HERE//
}
}
}).start();

What is the best practice to start a service every minute in android?

I am using AlarmManager of Android and scheduling a repeating alarm using elapsed_time_wakeup for every minute. This alarm fires of a service.
Service does its work (pinging the server(Facebook server in my case) to get data). Next I call onDestroy() of the service. So every minute Service starts -> Does work -> onDestroy()
Is the best way to do this in android?
Do you really need new service every minute? I think you want to start single service. That service does each minute check on server and reports success or error somehow? You want simple always running service with periodic action, not periodic service starting. In this case, starting new service would consume maybe more resources than check itself.
Just make sure service stays running. That might be case until you call stopSelf() from it and starting activity does not stop it also. You may want to run it as
private ping() {
// periodic action here.
scheduleNext();
}
private scheduleNext() {
mHandler.postDelayed(new Runnable() {
public void run() { ping(); }
}, 60000);
}
int onStartCommand(Intent intent, int x, int y) {
mHandler = new android.os.Handler();
ping();
return STICKY;
}
You might want periodic check only on Wifi connection or connection present. And maybe to stop checking when you already know about problem and are solving it. You may want to use startForeground() from Service to start some activity to control it and display results.

android and alarmManager

I write application which will use alarm manager. First I set up alarm manager to run some service every 20sec. Then service start some Thread. Here code of my service:
public int onStartCommand(Intent intent, int flags, int startId) {
ExtendedLog.i(TAG, "On start command");
Thread t = new Thread(wat);
t.start;
this.stopSelf();
return START_STICKY;
}
My problme is that this running properly only for few minutes. After that alarm manager starts service but thread does not start. I really dont know where is problem. Do anyone of you know what may be wrong with it? Thanks for any help.
Why are you stopping the service if you want the thread to keep running?
Looking in the Service documentation:
All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().
So since you did not stop your threads in onDestroy as requested , the system probably interrupts and stops them on its own.
What are you trying to do here? Starting a new thread & new service each 20 seconds is probably (I might even say obviously) not the best way to implement whatever you need to do... What is the code the runnable wat runs?

Categories

Resources