I am writing an app that connects to a Bluetooth device, continuously receives data from it, and stores in local db. Certain data received requires system alert to pop up. There is a main activity which just displays the status of connection and data received. It all works just fine so far, including the popups.
Since the app requires to be run in background I have implemented a "bluetooth connection" service that manages the BT connectivity, and displays ongoing notification in order to avoid being killed. For coding clarity reasons I would like separate background service to collect all data, and log it (instead of having BT service do all the work). I also prefer loose coupling between my app components, so am using GreenRobot's event bus for all IPC. As a result my BT connection service is completely unaware of any data collection/logging code - it just dispatches a message to event bus and I'd like to keep it that way.
Now I'd like to have my data collection/logging code to be run as another background service. Is there a way to ensure it runs as long as BT connection service is running? And without displaying yet another ongoing notification or tightly coupling the code between two services?
You could let your class extend service so in this case you dont have to make a notification for it. Basically it keep running in the background without the need of displaying notification on the status bar. Make sure before you exit your app to stopservice() otherwise it will keep running until the device restarted or in somehow the user force stop your app from application manager inside of the settings.
Related
I'm developing an Android app.
I want to continue to receive callback even if I close the app. (For example, Bluetooth connection or ConnectivityManager.NetworkCallback)
I know that such a way is a foreground service, but I don't want to use it.
Because if you use the foreground service, you have to make notification essential, but I don't want it.
Is there a good way to get callback even if you shut down the app without using the foreground service?
I have an application which is for searching colleges, and is running a background service to listen the server for updates, new messages, califications, etc. But in the newest versions of Android (10 and above) the service finish when the user close the app (in the foreground and background).
The question is: what Kind of service or worker (or something) can I implement to listen the server for real time notifications despite the app being closed?
What I tried: service, intent service, workmanager. This solutions finishes when the app is kill. And also foreground service (actually i'm doing this) that works well but has to show fixed icon to notify the user the service is working, and when the app have to show a new notificacion for other reason it won't change (it's like the foreground would have a exclusive priority).
What I don't want: do 'tricks' like send broadcast to another class and restart the service or trigger alarm manager. This things not work and if maybe works cant get so far.
Right now I have a server running on a desktop. I want to be able to start up my app, hit a button to start collecting data from this server, and only stop once I hit to button again. The user should always be grabbing data from this server after hitting the button, even if the app isn't active. So far I've considered setting up a Service or using Threads by themself.
A Service sounds exactly like what I need, but I've been told it isn't meant to sustain a long network connection. I poked through the BluetoothChat sample application and it didn't use a Service. Would a Service be the right thing to use then, or should I implement it with threads like the sample application does? The only reason I need a long connection is to listen for any error reports from the server. The other network stuff only happens when the user is directly using the app. I will have to use threads anyways because a Service runs in the same thread as the activity that calls it, but I guess my main question is whether I should scrap the Service part. Right now I have a basic Service set up that can handle messages sent to it and it seems really easy to use. The documentation on it is just all over the place, there needs to be a section saying "If you want to do X, then this is suggested!"
A Service runs on the UI thread, but an IntentService runs in its own thread.
It's ambiguous to say that the "app" isn't active. If you're running a Service, it's always active. An IntentService is active as long as it has finished the work in its onHandleIntent() method. None of the activities of the app may be active, which means that the app is in the background.
Other than that, I'd need to know more about what you're trying to do. In general, it's better to collect data in cycles rather than trying to keep the connection open constantly. For example, what do you do when the device loses connection to the Internet?
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.
I am trying to develop an application which will require a service to
run in the background. I am relatively new to android programming,
and after reading many posts, blogs, how-to's and books on creating
and managing services, I am still pretty confused about which model I
should try to use.
First, let me present (in general) the application requirements: I
need an application which will spawn a background process (service?)
which will connect to a bluetooth device. The bluetooth device is
designed to deliver data to the android device. The issue is that the
data could come in at any moment, so the bluetooth connection has to
stay active. Note that the application is a VERY SPECIFIC app and is
NOT intended for public use. I do understand the arguments for not
having background apps running all the time, but please understand
that this is a very specific application for a very specific client.
Now, in general, I think the program flow would be to start the
application (and launch a UI activity). Then I need to configure and
connect to the bluetooth device. At this point, the user should be
able to do other things - make phone calls, check their email, etc.,
while the bluetooth connection is still active and potentially
receiving data. If data comes in, a notification is fired, etc.
So here are my questions and concerns:
If I start an app (which spawns a UI activity and ultimately my
bluetooth connection service) but the app is killed, apparently, the
service handling the bluetooth connection is killed as well. How can
I keep that alive? I read that Service.setForeground() was
depricated, but even if I were to set it to the foreground, if the app
is killed, the service is killed as well. I need to have it run in
the background with as high of a priority as possible (again, I do
understand that this is considered "bad form", but this is a specific
app and this functionality has been requested by the client).
If I started the app (and the service, etc.), but the user, say,
answers a phone call, the app is put into the background. However,
let's say the user goes back to the home screen and starts a DIFFERENT
instance of the app, i.e., he doesn't hold down the home key to select
the already running app from the task manager but starts a completely
new one. If the service handling the bluetooth connection is still
running, how will this new instance behave? i.e., how can I get it to
connect to the bluetooth service which is ALREADY running in the FIRST
instance of the app instead of this new instance? Do I have to use
some form of a Remote service instead of a local service? This is
where I'm a little confused by things as it seems remote services and
defining an AIDL seems to create a lot of extra overhead, and since
I'm already creating a lot of overhead with the service running in the
background all the time, I want to keep that as small as possible.
How can I insure I am connecting to the same service already running?
1)
The service does not depend on an Activity. You can have it running on the background until you call stopSelf().
You can have a BroadcastReceiver that listens to the android.intent.action.BOOT_COMPLETED so your service is started when the phone is turned on.
2)
Your Activity should bind to the service. And get the info from it.
Check this question.