Message from Service to Activity never arrives in Handler - android

it seems I missed something important:
Until now I had an activity that starts an own thread. This thread sends messages from time to time using the sendMessage() method of a Handler that is located in same activity. That works fine.
Now I added a service doing some cool stuff in background. This Service itself tries to send some messages using the same way: calling sendMessage() of the Handler that is located in Activity. But these messages arrive only sporadically, many of them get lost.
So it seems there is something different in Messages/Handlers when a Service is involved?
Thanks!

It's better if you declare a local broadcast receiver in your activity to receive the information of the service, and then, in your receiver you can send the message to the handler.

Related

control a service from an activity

I have a chat client activity which continously filtes incoming packets using a while(true) loop. On the basis of message contained in the packets, I need to start and stop a service. The service performs an intensive long running task. Since, the service starts in the same thread of the caller Activity, I cannot start the service and also continue to filter packets, otherwise it shows an ANR dialog.
How can I keep both the activity and the service doing their tasks and also the activity to be able to later inform/stop the service?
I started the service in a new thread but that still gave an ANR.
Edit: Using AsyncTask and BroadcastReceiver works only if packet-filtering is stopped at the time of calling the service. Simultaneously doing both gives ANR.
Use a Broadcast Receiver and register with a particular intent-filter. Broadcast an intent whenever you need to do any processing based on the content of your chat messages. Within the receiver you could take whatever action you need to.

Relationship between broadcast receiver and Service

Im confused with Service and Broadcast receiver.what is the relationship between these two?why we have to call broadcast receiver when we start a service.Can anyone kindly explain the concept between these two elements
You don't have to register a BroadcastRecevier when you start a Service. That is, even if you don't register a BroadcastReceiver, our Service will work as expected. There is no must have dependency between the two.
As explained by Gridtestmail, a Service is a process you want to run in the background, without having an interface to the user.
A BroadcastReceiver is registered, when you want to be notified about certain events happening - for example, discovering a new bluetooth device or receiving an incoming call.
If you register a BroadcastReceiver for receiving incoming calls , then your Receiver's onReceive() method is called whenever there is an incoming all, so you can process it.
Similarly, for other event detection stuff.
I hope the concept is clear to you now.
Service: If you want to do something in background , this will be running always in background even if the application closed. You can create this in separate process and also you can give your service to other app if you want. Downloading any content or Music is good example
Broadcast Reciever: Usually system will send some info which can be recieved by your app if you would wish to ,by registering. And you can do something what you want when that thing happens by using onReceive method. Example is the system will send BroadcastReceiver when new sms arrives or Booting done
Example : Service and BroadcastReceiver

Stopping an IntentService from an activity

I have an IntentSerivce that runs in the background sometimes and it can be quite a long running process in certain instances. I give an option for the user to quit the application which basically just stops and polling and ignores any GCM push notifications. But if a push notification came in and the IntentService is taking a while to finish doing what it has to (gets information from a server and sends a notification to the user if needed, like a new message arrived or something).
Here is the problem, if the user elects to "Quit" the app while the intentservice is still running they will still get the notification which I do not want. I know that there is the stopSelf() method for the service but I need to stop it in an activity when I know the user "Quit" the application via a menu button. Sending another intent to the service does not work since the intents get queued up and calling context.stopService(intent); in my activity does not work either so how else can I stop it?
Are you passing a new Intent into stopService(Intent) or the original one used in startService(Intent). Passing the original Intent should stop the service.
Failing that you could use a Handler to pass the service a Message. Have the IntentService implement the Handler.Callback interface and create a new Handler(Handler.Callback) in your Activity, passing your IntentService as callback. Then implement the onHandleMessage() in your IntentService to call stopSelf() and have your Activity pass a message to it when you want it to stop.
Below code is perfectly working fine for me to stop IntentService from Activity:
stopService(new Intent(getApplicationContext(), MyIntentService.class));

android - SMS Receive Broadcast receiver getting aborted

I am developing an android SMS app which will not save the message in the inbox.
I need to verify the content of the message using a webservice call and then remove the broadcast.
In the onReceive() for SMSReceiver
if (messageBody.equals("somedata"))
{
Intent i = new Intent(context,Webservice.class);//webservice validation
i.putExtra("messageBody",messageBody)
startService(i);
// Stop it being passed to the main Messaging inbox
abortBroadcast();
}
The Intentservice for webservice call never gets executed.The receiver is aborted before this.
I am new to android,so please let me know if it right to do the webservice call in an intent service started in the onReceive() of the broacast receiver(SMS_RECEIVE).
Use logging to be sure that the equals() returns true. If that is the case, it might be that you're doing something time consuming in the onReceive() and the BroadcastReceiver gets killed. From documentation:
http://developer.android.com/reference/android/content/BroadcastReceiver.html#onReceive(android.content.Context, android.content.Intent)
The function is normally called within the main thread of its process, so you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed).
It may be spaces problem in your messageBody variable,
please try this,
if (messageBody.trim().equals("somedata"))

AsyncTask in BroadcastReceiver in Android gives sending message to a Handler on a dead thread error

I have implemented Push Notification in my appliction. Once the push message is received I call a webservice with the help of AsyncTask. This works fine when the application is being used or is in the memory. But if I stop the application from settings and then if the message is pushed to the device, there is an exception such as "sending message to a Handler on a dead thread". This is probably since the app is not live.
Can someone let me know if its alright to actually remove AsyncTask from push notification receiver and just handle the message?
Regards
Sunil
This is due to a bug in AsyncTask in the Android framework. AsyncTask.java has the following code:
private static final InternalHandler sHandler = new InternalHandler();
It expects this to be initialized on the main thread, but that is not guaranteed since it will be initialized on whichever thread happens to cause the class to run its static initializers. I reproduced this issue where the Handler references a worker thread.
A common pattern that causes this to happen is using the class IntentService. The C2DM sample code does this.
A simple workaround is to add the following code to the application's onCreate method:
Class.forName("android.os.AsyncTask");
This will force AsyncTask to be initialized in the main thread. I filed a bug on this in the android bug database. See http://code.google.com/p/android/issues/detail?id=20915.
IMO AsyncTask should be only used as a helper for background tasks related to Activities (that is, UI).
In your case I would use an IntentService, it is a Service that is prepared to execute background task. So:
A new notification is pushed to the device.
You receive the notification in your broadcast receiver.
You fire a IntentService to perform synchronization against the WS
The IntentService does its job, when finishes it raises a broadcast event.
In your Activity attach a broadcast receiver for the broadcast in step 4. This way your UI gets notified if it's present, else nothing bad happens. Optionally you can register a default broadcast receiver in your Manifest to handle the broadcast of step 4 and, for example, display a status bar notification.

Categories

Resources