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

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.

Related

Multiple services with same interval of time in android

How to run multiple services in background with same interval of time in android? . I tried with AlarmManager but in this it is not running with same intervals like every 5 mins(Sometimes its running correctly but not all the times). Please suggest me best way to achieve this. Thanks in advance.
To run the multiple services in particular interval, you can use timertask
Timer timer =new Timer();
TimerTask timerTask= new TimerTask() {
public void run() {
//TODO
}
};
timer.schedule(timerTask, 1000, 1000);
Example for Service,
public class ServcieSample extends Servcie{
public void onCreate(){
}
}
Inside onCreate you can create any number of threads or asynctask for background operations.

How should I run periodical task in 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.

stop service not working on logout click in android

i have service class , inside that class for every 15 minutes i am calling the webservice, if i logout the application the service should stop and webservice shoud not call , i tryed to use stopService but its not working please help me to do this
SERVICE CLASS:
`class GPSTracker extends Service implements LocationListener{} public Location getLocation()//using this i am getting the location
I Have used the timer to send the webservice
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
MultipartEntity params = new MultipartEntity();
try {
params.addPart("value", new StringBody("live_feed"));
params.addPart("latitide", new StringBody(String.valueOf(latitude)));
params.addPart("longitude", new StringBody(String.valueOf(longitude)));
params.addPart("security_id", new StringBody(Helper.loadSavedPreferences(mContext,"security_id")));
Log.d("Security ID", Helper.loadSavedPreferences(mContext,"security_id"));
new JSONParser(mContext, new GpsListener()).execute(params);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, 0, 1000 * 60 * 1);
In another Helper class i am just stoping the service but its not working
activity.stopService(new Intent(activity,GPSTracker.class));
You should bind your services onResume, and unbind them onPause. This should keep the service from working if you aren't in the application.
You could also call timer.cancel(), so long as you've stored a reference to the timer. Just be warned that you need to create a new timer to use it again.
Use the base context to stop when you click the logout button.
stopService(new Intent(this.getBaseContext(), GPSTracker.class));
bind and unbind service are to create a service connection between the service and activity, so that the activity can access the service though the service instance.

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).

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