Android How to implement services for time delayed actions? - android

I implemented some app, that waits about some time before action. User can go to preferences and define time to wait. My problem is now that if I press home button I can´t start any other app, because my app take all resources. I have an motorloa milestone and my code is (part of source code of waiting service) :
public void run() {
while(currentTime>waitingTime)
{ currentTime = System.currentTimeMillis();
Thread.sleep(1000);
}
//do Action
}
It is an simple thread, but it seems to be very ineffective. I would be very thanks-full for any help.

you can always use Handler to schedule a Message. But your application needs to be in running state to get a call in Handler's callback mathod(handleMessage(message)). Another option is to go for AlarmManger.

Use AlarmManager to schedule a PendingIntent to be invoked at your designated time.

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();
}

How to implement application idle timeout in android application?

Is there a way to implement timeout feature in the following scenarios?
A web application with html pages and native screens.
1.When the application is in the background for 5 min -> destroy the application.
2.When the application is in the foreground but not receiving any user interaction for 5 min ->destroy the application.
I think you can use this.
ApplicationConstants.TIMEOUT_IN_MS will be 300000 //5 min
private void timeout() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
System.exit(0);//close aplication
}
}, ApplicationConstants.TIMEOUT_IN_MS);
}
#Override
protected void onPause() {
super.onPause();
timeout();
}
Cheers,
Regarding background state:
There is no need to kill the app's process manually by default. The Android OS does this by itself if there is a need to free up resources for the other applications.
See this guide for a reference.
Though if you need to perform some background work during this "idle time", you may start a Service to perform those operations and then stop it from code.
Regarding foreground state:
I think the best approach to use here is to send Messages to a Handler of the Main thread of your application, since you do not know if the user will interact with the UI again after they leave. When the user comes back to the UI, you may clear the message queue, using Handler's removeMessages method.
I do not recommend you to finish the process with System.exit(0) in Android.

Android Service in background thread

I'm trying to create a service that runs in a given interval. The service's purpose is to update a database and when done notify an Activity with an Intent.
The service should also be callable from the activity when the user chooses to 'refresh'.
I have accomplished this, but I can't get it to run in a detached thread.
The service executes an update method in a Runnable:
private Runnable refresh = new Runnable() {
public void run() {
update(); //Runs updates
didUpdate(); //Sends broadcast
handler.postDelayed(this, 50000); // 50 seconds, calls itself in 50 secs
}
};
I have another runnable called ManualRefresh that is called via a broadcast from the activity.
However these runnables seem to be blocking the UI.
Need advice! :)
When you run a Runnable by calling it's run method, it runs on the current thread. To run on a background thread, you need to use new Thread(refresh).start(); (if the Runnable you want run is refresh).
You can also make use of AsyncTask for this, but that's more appropriate for an activity than for a Service. Information about using AsyncTask can be found in the API docs and in the article Painless Threading.
I suggest to write the service using the AlarmManager. The service will receive an Intent to tell it to periodically to update the database.
Once updated, you can notify the Activity with an Intent (as you mentioned).
When the user wants to manually refresh, have the Application sent an Intent to you service. Receiving the Intent from the AlarmManager or from the Activity would perform the same code.
You may also want to reschedule the alarm after a request to manually refresh.

Call a specific action in certain time in Android

What I want is 5 minutes after I open the application do a specific work.
I am not sure what I suppose to do.Should I create an AsyncTask in onCreate method of my main activity or a thread? Or should i do something completely different?
This may help: http://developer.android.com/reference/android/app/AlarmManager.html
Your question is a combined question asking how (way) to perform a task as well as how to schedule it.
Decide what is the task you want to perform. If its a long running task, use either AsyncTask or IntentService
To schedule the task you can either use Hander postDelayed, Timer or AlarmManager. My pref. would be a one-time AlarmManager - Once registered, even if you app is not running, the callback will be triggered.
You could use a Handler :
new Handler().postDelayed(new Runnable() { public void run() {
//your delayed action here, on UI Thread if needed
}
}, 1000 * 60 * 5 );
Regards,
Stéphane

Android Approach: How to design a service which checks frequently for a specific event

I've been working with Android for just a couple of weeks now and have some troubles with Services.
I have a background service running which checks every minute or so if a scheduled action needs to be executed. Second use is to store some user data and make them available for my activities. There are two issues:
The service gets binded by my main application but it seems that once I quit the main app, the service gets destroyed too. Why is that and what can I do against it?
The service doesn't run forever but seems to get stopped at a random point.
I understand why Android kills my service and so on and I also tried to use the AlarmManager instead of using a Timer in the service. These approaches somehow work, but they are just not versatile and dynamic enough.
So how can I have both an regular schedule check and some kind of data-sharing the right Android-like way?
You need to read about
local service
and remote service
You can use following link to see difference or goto http://developer.android.com/guide/topics/fundamentals.html link to read about fundamental component of android.
http://saigeethamn.blogspot.com/2009/09/android-developer-tutorial-for_04.html
http://saigeethamn.blogspot.com/2009/09/android-developer-tutorial-part-9.html
You can run a thread using TimerTask and Timer to schedule your task at regular interval
I was using following code to show result on UI.
Handler handler = new Handler();
Timer t;
TimerTask timeTask;
protected void usingTimerTask() {
t = new Timer();
timeTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
btn1.setText("Hi");
}
});
}};
t.scheduleAtFixedRate(timeTask, new Date(), 1000);
}

Categories

Resources