In my application i start an service from a activity using startService command. This service is used for uploading file so it will take time.
So what i want is my Activity should be finished and srvice should keep on doing its work. For this purpose after calling startService() i call the activity finish also.
Because of this my service stops in between abruptly while if i dont call finish of activity everytihng works fine. I want to know how to make it possible so that service keep doing its work while Activity (who started this service) is finished.
Thanks in advance for help.
You should do your uploads via IntentService because:
•The Service runs in background but it runs on the Main Thread of the application.
•The IntentService runs on a separate worker thread. so it runs your codes even when your application's Activity isn't open
Use something like this:
package com.example.test;
public class MyService extends IntentService{
public DownloadService(){
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent arg0){
// Here is your codes
}
and here is a good sample ;-)
Related
I have implemented a simple Android Service that, by default, is deployed within the same process as my app / apk. I want the Service running concurrently with each Activity. To make that happen, in each Activity.onStart() and Activity.onStop() implementation, I have logic that invokes Activity.bindService() and Activity.unbindService(), respectively.
Well, all of this works fine, but it feels awkward. Is there any other way to make sure the Service is continuously running and bound to all Activities without having to re-invoke Activity.bindService() and Activity.unbindService() for each Activity? Should the Service in this case be declared as a stand-alone process?
Also, my Service starts a separate thread, but never stops it. Should my code stop the thread? Is there a chance the thread could be orphaned? Starting / stopping the thread with OnUnbind / OnRebind seems like overkill.
Create a base Activity and call bindService in onStart, unbindService in onStop.
public class BaseActivity extends Activity {
#Override
public void onStart() {
// ...
bindService(intent, serviceConnection, flags);
}
#Override
public void onStop() {
// ....
unbindService(serviceConnection);
}
}
This will make sure every activity that extends base is bound to the service.
When last activity is unbound from the service, it will be stopped. If you want to avoid that, call startService first, and then bind to it. This will prevent service from stopping even if you don't have running activities.
Should the Service in this case be declared as a stand-alone process?
In your case, you don't need a separate process for your service.
Also, my Service starts a separate thread, but never stops it. Should my code stop the thread?
If you want to stop your service, you should stop your thread because thread is a GC root, and all objects accessible from it will remain in memory. So, infinite thread that is not used is a memory leak.
You can implement threading different ways depending on your requirements. You can either implement a regular thread in your Service, or a ThreadPoolExecutor or a Handler. Pick a solution that fits to your needs.
You can start your Service in your custom Application class. This way the service will be started only when your application is started.
For example:
public class MainApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
starService();
}
public void starService() {
Intent i = new Intent(this, YourService.class);
this.startService(i);
}
}
While the other answers ere good, you might want to ask this:
"Does this service needs to keep on running while the application is not, and will not run?"
If so: create as an independant serviceIf not: extend a helper class that implements the bind/unbind and have Activities extend that.
I m new in android, I'm not much aware about services.i have an activity class with a UI, i want to make this activity class runs in background, when i click the back button. how to make my activity runs in background like a service, plz help me..
You cannot really run an Activity on background! When an activity is not on foreground it gets to onStop and then the system could terminate it, to release resources, by onDestroy method! see Activity Lifecycle
In order to run on background you need to create a Service or IntentService
Checkout android javadoc about Services here and here or IntentService
and here is a third-party Android Service Tutorial
Edit: you may also need a communication between your service and your activity so you can get through that: Example: Communication between Activity and Service using Messaging
If you simply want your activity runs in back Try using
moveTaskToBack(true);
It seems like you want to run an activity in background when it quits. However, activity can't be run unless it's on foreground.
In order to achieve what you want, in onPause(), you should start a service to continue the work in activity. onPause() will be called when you click the back button. In onPause, just save the current state, and transfer the job to a service. The service will run in the background when your activity is not on foreground.
When you return to your activity later, do something in the onResume() to transfer the service 's job to your activity again.
You should read the developer guide on Threads: http://developer.android.com/guide/components/processes-and-threads.html
Specifically the function doInBackground()
Example from page:
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
The doco for startService states "If this service is not already running, it will be instantiated and started (creating a process for it if needed); if it is running then it remains running."
I'm finding that each call to startService appears to be starting a separate instance of the service, in that the work that the service is doing (in my test case, trivially writing to a new log file) is being done again for each call.
I'm trying to detect the service by looping through ActivityManager... getRunningServices(Integer.MAX_VALUE)) but it's not showing up.
Android 2.3.3 on SGS 11
I'm missing something here. I understood that the Service's onCreate() method only gets called when it's created, and that since I have a continuous process running in the Service (the
In my Activity's onResume method I'm starting the service ("myService")with:
Intent intent = new Intent(this, myService.class);
startService(intent);
In MyService I have an onCreate like
#Override
public void onCreate(){
super.onCreate();
...
from where I set a timer, using a TimerTask, which writes to a log file once/second.
This works as expected - I can see the log being written.
In the Activity's onResume method, before calling the StartService method, I'm checking to see if the myService service exists by calling a checkForRunningService method containing
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (service.service.getClassName().contentEquals("com.gpsanimator.startrax.myService")) {
Toast.makeText(getApplicationContext(), "Service IS SO running: ", Toast.LENGTH_SHORT).show();
return true;
}
This never finds the myService service, even though it appears to be running as it's happily writing to the log file.
Eeach time I resume my Activity, the onCreate method of my myService service gets called - it generates a new log file and starts writing to it as well as the original log file being continuously updated.
Doesn't the Service get started the first time the startService is called? And then continue running? Shouldn't subsequent calls to startService() find the Service already running and therefore not trigger the onCreate() method again? But that's not what I'm seeing. It seems that every call to startService() is triggering the Service's onCreate() method.
It's obviously more complicated than this, and I would like to get to the bottom of it.
It all depends on which method you're putting the code in.
When you call startService only one service will be created at a given time. If the service already exists it will be reused. So the code in onCreate() will only be called if a service did not already exist.
However, each time you call startService the code in onStartCommand() will be run no matter what.
So yes only one instance of a service ever exists at a given time, but calling startService can have an effect.
The problem was I had declared my myService class to extend IntentService, not Service!
Once I fixed that, it all worked as per the book!
IntentService stops immediately (automatically) after work is performed, BUT if you start it again till work finishes you are reused existing service instance and onCreate isn't called. So please be careful with IntentServices.
You are extending IntentService which will work as a worker thread. The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. So in your case your service stop itself after completing the task so it creates multiple times. You should use Service class and bind with the component.
I Need some help here, I have a service which I can start or stop whenever I want and using the onStart() command to pass some extras using putExtras() from my activity
But I need some serious basic instructions on how to interact with the already created service.
Please don't refer me to another webpage which already have some implementations, just give me the needed code to interact from my UI activity to the service:
something like this:
public class myActivity extends Activity {
Object ReceivedObjectFromService;
onCreate()
{
some stuff here
myMethod()
}
public class myMethod()
{
//do some stuff with the ReceivedObjectFromService
//Don't know how to call this method from the service btw
}
please some help, I don't understand the tutorials on how to interact service to activity or viceversa
Interaction with already created service is no different to starting a brand new service. You just simply call startService() so your client code is no different.
Now, the part which is different is the service itself. In your service, onCreate() must start a background thread or a timer to carry on doing a work. onStart() will receive all startService cases and must in fact add the data it receives in the Intent to an internal list or queue and then in the timer's callback start processing from this queue.
Now you can pass any messages or data you want (even closing the service) using startService and passing data in the Intent that your service understands.
Hope this helps.
I have 3 classes in my App.
Class A extends Activity
class B extends BroadcastReceiver
Class C extends Service.
When I run the App. which one of this will be called first, I know android doesn't have a entry point. I am blocking the incoming call in class B , and I am calling the service from activity > this service will call BroadcastReceiver > here is where I block the calls.
When I run the code from eclipse to Droid, it is constantly blocking the call, even before I start the App. does any one know the reason. Thank you very much .
Service,
Another application component can start a service and it will continue to run in the background even if the user switches to another application.
So that is how you broadcast receiver is called.