Background process running in android - android

I'm making an app in which i want a process always run in background e.g in facebook we got a notification and it will notify in our app. Kindly text.

Try Services and BroadcastReceiver to do this.

guess you need to explain the function you want in a detailed way.
Usually we will use a Service
or a Intent Service to do what you mentioned. If you want to detect a change in your application or the phone, you may register a broadcast receiver or a Content observer in the service depends on the function and effect you want.
But bare in mind that, service do not have UI so you should avoid to interact with users while using Services.
From my understanding, service can do most of the tasks you want. One example is play music. You can run a service in foreground if you want to ensure that the services is harder to be killed by the system when memory is low.
Intent service is used to handle asynchronous requests (expressed as Intents) on demand one followed by another. One good example is downloading a file
For Content observer, you will observe a content and the observer will react to if when there is any change from the "OnChange" method.
For broadcast receiver, usually we will use it to observe something happen, for example, screen unlocked, boot completed, sms received.
It really depends on your needs in order to decide what kind of services you want. Please explain in details in order to get more information.

Related

Android Notification Service

I have some doubts about the properly implementation of services and broadcastreceivers.
I have made an app in which there are novelties. Some novelties are important, so in the DB they have a field in which they store if they are important or not. If they are, the app should check if the last novelty seen by the user is the latest one. This should trigger a notification if there are important novelties that were not seen by the user.
I know how to show notifications in Android, and I have a Method in my Web Service which shows if the user has novelties to read or not. I just need to know how to make my app consume this at random times and without being opened (just like Whatsapp does).
I have read the BroadcastReceiver and Services documentation, but I don't know how to do this in an efficient way.
Do I make a BroadcastReceiver to call a Service at the Phone's Boot? And make this Service to check at random amounts of time?
Thanks a lot!
What you want is a foreground service with a BroadcastReceiver that starts the service on boot. View this answer and make the required changes to use startForeground() instead of startService.

Service or Broadcast receive for scheduling long background work (e.g. SMS scheduling ) ???

I need a help to develop a apps for sending sms in future time by scheduling the time and date .... Please help me by suggesting or give some example....
First of all, you need to know how to send a SMS using Android API. For that you can check this example which explains it:
http://www.mkyong.com/android/how-to-send-sms-message-in-android/
For scheduling tasks, just take a look at ScheduledExecutorService. Joining both ideas you will get what you want for sure.
Edit:
As asked by #BDAndroidLover about long background works, here is the description and aim of a Service in Android:
A Service is an application component that can perform long-running
operations in the background and does not provide a user interface.
Another application component can start a service and it will continue
to run in the background even if the user switches to another
application. Additionally, a component can bind to a service to
interact with it and even perform interprocess communication (IPC).
For example, a service might handle network transactions, play music,
perform file I/O, or interact with a content provider, all from the
background.
Because of that, a Service is the best solution for that purpose.

Where I should use Service , AsyncTask and Broadcast Receiver?

I'm in little bit confusion where in what case I need to use application components like Service, asyncTask and Broadcast Receiver.
Can any one explain what the exact difference between these there and where I need to use these components?
AsyncTask is a friendly way to create a new thread that performs some work asynchronusly.
A Broadcast Receiver is something like an Event Handler for system events. It can run in
background and perform an action when something happens, like turning the phone off or turning wifi on..
A Service is just an app that works in background (like a daemon) and serves information to an app or just performs tasks.
Sorry for my English, I try to let me understand but it is not my mother tongue
I will get straight to where I have applied these three in my projects so far:
1.Service:Something you want to perform in the background without any user interaction.For instance fetching location data continuously or sending some data continuously to your server.You can also use services to perform tasks every few time units.For example sending ten minute background updates.
2.AsyncTask:Making a new thread of execution.Best use I have encountered so far is calling a web service..I did the following using an AsyncTask for web service calls
1.Display Progress bar in onPreExecute()
2.Perform my web service calls in doInBackground(Params...)
3.In onPostExecute(Result) update the UI or do some other stuff with the response from the web service.
3.BroadCastRecievers are like global recievers for your app.They can listen for both System events like a phone restart or a custom event within your app.I used them for starting a service when the phone was restarted,which stopped when we switched off the phone.
Let me explain with a usecase, so you understand it better -
AsyncTask - Want to get something from the server, or post something to the server? If we do so on the main thread, the user won't be able to interact with the app. So Asynctask is used, and it performs the network activity in a different thread.
Service - Want to manage something in the background? Like get the users' location every 10 minutes or 1 hour, or alert the user when he is crossing a particular area based on the location. The Service makes the app run even when the app is not opened (the user might be doing something else, or the phone is locked, the Service still runs in the background).
Broadcast Receiver - Assume, you are tracking location and storing locally (when the internet is down). Not when the internet is up, you want to send all of them. So you register with the OS, that you want to listen for that specific event, and you get control.
Or when you want the server to know that the device is restarted, then we just have to implement it.
Clear?
A service and its local memory-variables are loaded into memory and is always running
A BroadCast receiver is only garanteed to be in memory and running while processing an event.
A Broadcastreceiver can be removed from memory by the operating system if the memory is low.
"Service" is a component which runs in the background, without interacting with the user. Every developer can create new Services in his application. Services support true multitasking for Android, as they can run in their own process.
"AsyncTask" encapsulates the creation of Threads and Handlers. An AsyncTask is started via the execute() method.the execute() method calls the doInBackground() and the onPostExecute() method.
Mostly main purpose to download something without user interaction.
"Broadcast receiver" is a class which extends BroadcastReceiver and which is registered as a receiver in an Android Application via the AndroidManifest.xml file(or via code).you can register a BroadcastReceiver dynamically via the Context.registerReceiver() method.
The class BroadcastReceiver defines the onReceive() method. Only during this method your BroadcastReceiver object will be valid, afterwards the Android system can recycle the
BroadcastReceiver.

IntentService, Service, or AsyncTask

What would be the best way to implement this. I have an Android app that will use my python server to allow communication between 2 phones in rounds. Rounds mean that they can't talk to each other until a round start and once they send a message they can't send another until the other person responds which will then start a new round.
I was thinking I would use the IntentService but it seems wrong to have the server constantly starting and stopping and I don't won't to have to worry about the issues with asynctask or is that the best way to handle it. How could I have a service that should receive and send messages to the client, seems services are more one way things?
Intent services are nothing more that worker threads that are triggered by intents, execute their actions in a separate thread and then get shut down. They are designed to be started and stopped.
If you need to perform stuff like an http get, or in any case interaction that do not require to stay connected to the server, use intent services and get your activities notified using broadcast events.
If your app needs to stay connected with the server (i.e. permanent tcp connection), the way I'd go for is to have a service (not an intent one) that performs the networking stuff using an asynctask or a more classic thread hosted in the service. You can then make the activity interact with the service using bindToService() .
I'd recommend not to use asynctasks inside an activity. You will risk to loose the server response in case of horizontal / vertical view changes, as oneilse14 stated in his reply.
I highly recommend the IntentService/Broadcast Receiver route. Avoiding the nasty configuration change issues associated with AsyncTask will make your life ten times easier.
As far as i understood your problem is of type worker-queue model Producer-consumer model). Intentservices are meant to do that. You should use services if and only you need to do multithreading. You do can communicate with Activity and Service by using IBinder interface.
Asynctask are just a specialized threads so that you can update your UI easily. But for your case IntentService seems to be best option.
I would use an Alarm, which is scheduled via the AlarmManager, as then it can be set to check if the round has started/turn. It has the advantages of a service but not the horrors of battery drain. It takes a frequency to how often the Alarm should run, which even includes enumerations of time (e.g. 1 hour/day/week).
When the Alarm runs it could poll to see what the current state is and react accordingly. For example a notification could go into the status bar and phone could make an audible noise and vibrate.The benefit of this is that the user does not have to keep the app running as the Alarm will trigger a broadcast receiver.
An example of the Alarm code: http://www.androidcompetencycenter.com/2009/02/android-basics-alarm-service/

Android independent services how to?

I was wondering if there is a way to create a service that will run as it's own process independent of an activity. I would want to service to run in the foreground so it would not be killed and also accessible to other .apk that wish to use it. How can I do this? I've read so much that its made me a little more confused then I initially was. Any help would be much appreciated.
To clarify. I would like to run a service that can communicate with many .apk's. It is an in-house application with no market value. What I am trying to do is make service that .apk can register there content providers with so all .apk's using this service have a list of all other .apk's content providers to use as pleased.
Services are by their nature independent of Activities. You don't need one to run the other. Services always run in the background and usually don't get killed unless they take too many resources.
Depending on the type of interaction you want between the Service and Activities you'll need to define the appropriate intents or maybe use a ContentProvider.
UPDATE:
In the case you described above, simply have each content provider register with service using an intent that specifies the URI needed to access that content provider. The service would then keep a list of all registered content providers and their URI's.
When a new activity wants to get a list of all available ContentProviders it can query the service with an intent asking for a list of providers. The service would then respond with an intent that would contain the list of providers and URIs.
Using this information the individual activities could then decide which content providers they want to interact with.
How can I do this?
You don't, insofar as you do not need it to be "as it's own process". Just start up the service via startService() and have the service call startForeground(). It can be part of the same process as the activity, and the user will be able to navigate away from that activity if desired and the service will remain running.
I would want to service to run in the foreground so it would not be killed
Note that users are still welcome to get rid of your service. startForeground() will reduce the odds of Android getting rid of the service on its own.

Categories

Resources