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.
Related
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.
I use Volley library to connect with server in my app. Now, I have to send request in background every 5 minutes also when app is not running (killed by user). How should I do it? With background services, AlarmManager (Google says that it isn't good choice for network operations) or something else?
Or maybe SyncAdapter will be good for it?
You can use a TimerTask with scheduleAtFixedRate in a service class to achieve this, here is an example of Service class, you can use it
public class ScheduledService extends Service
{
private Timer timer = new Timer();
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sendRequestToServer(); //Your code here
}
}, 0, 5*60*1000);//5 Minutes
}
#Override
public void onDestroy()
{
super.onDestroy();
}
}
You can use sendRequestToServer method to connect with the server.
Here is the manifest declaration of the Service.
<service android:name=".ScheduledService" android:icon="#drawable/icon" android:label="#string/app_name" android:enabled="true"/>
To start the service from MainActivity,
// use this to start and trigger a service
Intent i= new Intent(context, ScheduledService.class);
context.startService(i);
I prefer to use Android Handler because it is executes in UI Thread by default.
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
sendVolleyRequestToServer(); // Volley Request
// Repeat this the same runnable code block again another 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
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.
i have created one intent service. Now I want to stop that service from activity how to stop that service? My code is:
MyActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent(this, myService.class);
intent.putExtra("myHand", new Messenger(this.myHand));
startService(intent);
}
myService.java
public class myService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
String signal = intent.getAction();
if (signal != null && signal.equals("stop")) {
stopSelf();
} else {
t.schedule(new TimerTask() {System.out.println("print")}, 0, 10000);
}
}
}
to stop service on click of button
Intent in = new Intent(this, myService.class);
in.setAction("stop");
stopService(in);
can anybody help me to stop service?
From the docs for IntentService
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
In other words, you don't have to stop an IntentService - it will terminate itself when it has no more work to do.
EDIT:
Looking back at your code, it seems you don't wan't to stop the IntentService you want to stop the TimerTask???
t.schedule(new TimerTask() {System.out.println("print")}, 0, 10000);
I don't know what t is but I'm guessing it's a Timer. If that's the case it will be running with its own Thread and attempting to terminate the IntentService is pointless - kill the Timer instead.
Also, why are you using an IntentService to create any type of object which maintains its own thread of execution?
Now I want to stop that service from activity how to stop that
service?
IntentService stops itself, you shouldn't, you can't call stopSelf().
When all requests have been handled, the IntentService stops itself.
From what I know, IntentHandler creates a separate new thread, does its work, and kills itself.
So I don't think you need to explicitly stop it from an activity.
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...