Foreground Service or standard service? - android

I have Fragment which is basically a View that shows any incoming messages for a user. I want the create something that will check every 5 seconds for any new messages, and if found will append them to my ListView which holds the messages. My question is, from what I have read, a Service is the way to go with this. However, since I will be communicating with the app from this service I'd like to know which service I should use.
Should I be using a Foreground service, or just a standard Service?
My goal is that where ever the user is in my app, I will be able to receive some notification that a new message has come through and then perform a function when that happens.
I want to code this properly and according to best practices.

If you just want to call a method on your service when user is in your app, you just need to use a sticky service, but if you want to call this method even when user swipe your app away from recent apps you should use not_sticky service.
Foreground service are most used for cases that u don't want your task stop even for a second after swiping your app from recent apps e.g. playing music in background.
But in your case the best choice is to use postDelayed() and set 5 seconds delay for it and get rid of service.

Related

Background process running in 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.

Android service not starting/stopping as expected

I have been given multiple solutions to what I thought would be a common scenario. Unfortunately, none seem to work as expected.
I have created a pretty simple android game. The users can invite friends to play and there are a few activities they are routed through during the game lifecycle. All turns and data is stored in a remote server which is exposing the data through web services. Every time an invitation is sent, or the opponents complete their turn, the user is prompted via the service to play their turn.
The service prompts the user using a standard android notification telling them it's their turn. I don't want the service to poll the web service or present notifications while the user is viewing the game (they'll already know if it's there turn).
I have tried the following solutions without any success.
Start the service in the onPause method of the main activity and stop the service in the onResume method of the main activity.
Problem - Each time the user leaves the activity for another one the service starts. The user may be writing something or creating an invitation and they are prompted to take their turn.
Bind each activity to the service and set a boolean (running) flag in the same onPause/onResume methods of all activities.
Problem - This seems logical, but for some reason the service never presents a notification. This is likely user-error, but I'm not sure this is the correct solution anyway.
Start the service in the onPause method of all activities and stop the service in the onResume method of all activities.
Problem - Based on the toasts I'm presenting on the screen showing the state of the service this works as expected. The problem is the user is presented with notifications while the service is off. Apparently my toasts are misleading.
Any help is greatly appreciated. Sample code is not necessary, but would be appreciated if the solution is any more complex than the concept described above.
Thank you.
Don't use a service, use the Google Cloud Messaging and in the receiver of the broadcast, check the state of the game and then decide whether or not to show the notification. Polling is generally bad, uses data and battery unnecessarily.

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.

Registering a Broadcast receiver for android.intent.action.NEW_OUTGOING_CALL and ask the user what to do?

I know how to implement a BroadcastReceiver that is notified a new outgoing call is starting.
I also know how to eventually drop the call and handle it within the application.
What I'd like to know is if it is reliable to ask the user whether to drop it or not?
As far as I know the application has a limited amount of time to return from the RroadcastReceiver.
How long is this time?
Have you ever implemented it?
EDIT
Trying implementing it I realize that there is a bigger problem. In a BroadcastReceiver you can't show a dialog. Form the doc:
In particular, you may not show a dialog or bind to a service from
within a BroadcastReceiver. For the former, you should instead use the
NotificationManager API. For the latter, you can use
Context.startService() to send a command to the service.
The reason is that you can't perform AsyncTask. I thought I was going to use signals to implement it but you can't do it because the broadcast-receiver is started in the main thread and you can't make it waiting...
Is this right?
As far as I know the application has a limited amount of time to return from the BroadcastReceiver. How long is this time?
Formally this time is about 5 seconds - after 5 sec. while system main thread can't process system messages Android should throw ANR (Application Not Responding) dialog and force close your application.
More generaly - BroadcastReceiver onReceive() method should finish as soon as possible.
If you want show some UI elemets to the user, I think you should start your own Activity for that purpose.

Set event reminders in android with data fetched via webservice call

I am working on a small project. We need to do the following:
Have a background service/whatever running on your android ph which
listens for a sms with some specific content in the msg body
On encountering that specific content, make a webservice call to a
remote server to download some event data
Set the fetched event data as reminders in the calendar
All the above must be done without any user interaction.
I have managed to do #1 via a broadcast receiver. Didn't need to run a service for it.
For #2, I plan to call the web service via the Broadcast receivers onReceive() method and get the data. Once I have the data, how do I go about setting the same so that the user gets his/her timely reminders based on the same? There is no activity opening up or anything that the user can see. He should just get the reminders (even if he restarts the ph).
Any help will be much appreciated. Thanks!
For #2, I plan to call the web service via the Broadcast receivers onReceive() method and get the data.
Please don't. This will be unreliable and will freeze your UI if you happen to have the foreground activity. onReceive() is called on the main application thread, and Android will terminate your code if it thinks you are spending too much time on that thread, even in the background. Please delegate this work to an IntentService, which has a background thread and automatically shuts down when there is no more work to be done.
Once I have the data, how do I go about setting the same so that the user gets his/her timely reminders based on the same?
On Ice Cream Sandwich (Android 4.0), you could add events to their calendar.
Before that, roll your own reminder mechanism using AlarmManager.
There is no activity opening up or anything that the user can see.
You have no choice but to supply an activity. Otherwise, your app will never run on Android 3.1+. They will need to run your activity once to enable your app, then again every time after they elect to kill off your app via a task killer or the Settings application.

Categories

Resources