How should I run periodical task in android - android

I'm writing application which need to periodically (around about 15min) download JSON data from server in the background and notify user with Notification.
I don't have a lot of experience with android coding and I'm asking how I should do that correctly and with best coding practises?
I don't need too much precision, AlarmManager with inexact repeating should work perfectly. I know how use BroadcastReceiver to receive BOOT_COMPLETE and start service. However I don't know how can I set AlarmManager to run specific action in Service and if I should do this in that way? I don't want use android mechanisms in way that has not been provided.

Use the class TimerTask:
private TimerTask timerTask;
private final long PERIOD_TIME=1000 * 60 * 15; //15min
#Override
public void onCreate() {
Timer timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
//Your request JSON
}
};
timer.scheduleAtFixedRate(timerTask, 0, PERIOD_TIME);
}

Use AsyncTask for getting info from server. In onReceive method of Receiver class create new AsyncTask object and execute it as below:
private class GetContent extends AsyncTask<String,Void,String> // Assume class name
extras = extras.getString("json");
GetContent().execute(extras);
In default function of AsyncTask doInBackground, retrive data and return JSON. In the other default function onPostExecute, create a NotificationCompat.Builder object and notify.

Related

Implementing an android service for polling at regular intervals

What is the best way to implement an android Service (not IntentService) which polls a device using SNMP at regular intervals? I've tried implementing it with a Handler.postDelayed(Runnable) within onHandleIntent of IntentService. But later found it cannot be used in onHandleIntent() from this answer. My code just would not execute the runnable part.
make an IntentService not sleep until it executes a handler.postDelayed runnable
My code goes like:
public class MyPoller extends IntentService {
//Variable declarations
protected Handler handler;
public MyPoller() {
super("My service");
}
#Override
protected void onHandleIntent(Intent intent) {
.......
.......
runable = new Runnable() {
public void run() {
//My code here
handler.postDelayed(this, poll_interval);
}
};
handler.postDelayed(runable,poll_interval);
}
}
So I thought I could implement the same in a service, but I don't know how to implement this recurring task in a service also running it in a new thread. I found few answers demonstrating different ways of running recurring tasks in a new thread in a Service, but I'm confused.
Can someone suggest some way of implementing the same in a Service? It would be of great help. Thanks in advance.

AlarmManager Calling Function in Same Class

I am trying to give a LocationClient a two-minute period to connect before calling getLastLocation on it. Initially I implemented this with a Timer (and TimerTask), but because Timers do not work in sleepmode, I would like to translate it to an AlarmManager. However, I am a bit confused as to how to do this, considering an AlarmManager calls another class, whereas I want to remain in the same class and simply delay for a two-minute period.
This is how it looks with a Timer.
Timer theTimer = new Timer();
theTimer.schedule(new TimerTask() {
#Override
public void run() {
if(checkIfGooglePlay() && checkTime()) {
getPostLocation();
stopSelf();
mLocationClient.disconnect();
}
}
}, TWO_MINUTES);
Alarm Manager calls a broadcast receiver via a pending intent. Just make that BroadcastReceiver implementation a private subclass of the class that registers it. That way it has full access to class member variables and functions.
You may try using Java's Thread.sleep(). It's a static method so you don't need to instantiate a new Thread. It throws a InterruptedException, which, in simpler cases, shouldn't bother you.
From http://developer.android.com/reference/java/lang/Thread.html:
Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds and nanoseconds).

Is it possible to have a AlarmManager inside a Service class?

For example my app, it starts and runs the service(which is meant to check the database for new messages) but as far as I know you can have a AlarmManager to keep opening the Service if so is not opened.
But can you have aAlarmManager inside the Service class to keep on checking for new message in the database? Instead of re-opening the Service class just keep checking the database?
I want to know if it is possible to have a AlarmManager inside the Service class to keep checking the database every X seconds, because the Service will open when the App is Launched
The real question:
Is it possible to have a AlarmManager inside the Service class that runs a Method() to check a database?
Use a Timer
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
/**
*
*Do something. CODE HERE
*/
}
}, 0, 30000); //30000 = 30 Seconds Interval.

How to use thread / timer in android service and update UI?

I am developing an android application which will start a service.The service will execute some code after every fixed interval of time and end the result to the activity.The activity should display the result to the user.
First I tried it with a thread.
For the service to execute after a fixed interval I create a thread - execute the code, get the result - send this result to activity for display - put the thread to sleep for a some fixed time interval.
But it is not working as expected.The code is executed by the thread. The thread goes to sleep and then the result is sent to the activity at the end after the sleep time interval. The requirement is the UI must be immediately updated after the result is obtained by the thread code execution.
I have also tried using Timer and TimerTask. But it gives the same result as above.
Please help me on this.
Service class
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
td = new ThreadDemo();
td.start();
}
private class ThreadDemo extends Thread
{
#Override
public void run()
{
super.run();
String result = //code executes here and returns a result
sendMessageToUI(result); //method that will send result to Activity
ThreadDemo.sleep(5000);
}
}
private void sendMessageToUI(String strMessage)
{
Bundle b = new Bundle();
b.putString(“msg”, strMessage);
Message msg = Message.obtain(null, 13);
msg.setData(b);
}
Activity class
public class MyActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
class IncomingHandler extends Handler
{
#Override
public void handleMessage(Message msg)
{
System.out.println("in ui got a msg................");
switch (msg.what)
{
case 13:
System.out.println("setting status msg..............");
String str1 = msg.getData().getString("msg");
textview.setText(str1);
break;
}
}
}
}
The broadcast receiver is much better to use in your case.
Register it in activity and send broadcasts from your run target
Use LocalBroadcastManager. Your service will create a local broadcast and it will be available to your application. You can write a proper handler for that notification in your application and update the user interface accordingly.
Put the following code in your service
Intent i = new Intent("NotificationServiceUpdate");
LocalBroadcastManager.getInstance(this).sendBroadcast(i);
In your application, put the following in the activity which you want to update
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("NotificationServiceUpdate"));
Now your activity will get a notification whenever the service broadcasts the completion of task. You can further make this broadcast private to your application.
see here my answer about the ScheduledExecutor:
how to call a section of code every second in background in Android
and use the message to UI just like you're currently doing.

how to reference object created with Intent / startService

If I create a service in my app's onCreatelike this:
Intent srv = new Intent( this, MyService.class );
startService( srv );
how do I get a reference to the service object and how does the service object reference the app which launched it?
(Yes, I have listed the service in my AndroidManifest).
There are a few ways to handle this. You can bind to the service (bindService) where you will be called back with an IBinder interface.
Another approach is to just keep calling startService() with different intent data as a way of messaging to the service, with intent extra data containing message specifics.
Finally, if you know the service is in the same process, you can share the service instance in some static memory.
Building a Service
First of all, we need to create the Service in the AndroidManifest.xml file. Remember, that every Activity, Service, Content Provider you create in the code, you need to create a reference for here, in the Manifest, if not, the application will not recognize it.
<service android:name=".subpackagename.ServiceName"/>
In the code, we need to create a class that extends from “Service”
public class ServiceName extends Service {
private Timer timer = new Timer();
protected void onCreate() {
super.onCreate();
startservice();
}
}
This is a way to create Services, there are others ways, or the way I use to work with them. Here, we create a Timer, that every X seconds, calls to a method. This is running until we stop it. This can be used, for example, to check updates in an RSS feed. The “Timer” class is used in the startservice method like this
private void startservice() {
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
//Do whatever you want to do every “INTERVAL”
}
}, 0, INTERVAL);
; }
Where INTERVAL, is the time, every time the run method is executed.
To stop the service, we can stop the timer, for example, when the application is destroyed (in onDestroy())
private void stopservice() {
if (timer != null){
timer.cancel();
}
}
So, this application will be running in the background...

Categories

Resources