Issue
I'm trying to connect to a Service
using bindService()
.
I am able to obtain reference to the Service
in onServiceConnected()
method of ServiceConnection
.
My question is if I declare a method say downloadFile()
in Service
and call it through the Service
object from an Activity
rather than calling startService()
and then calling downloadFile()
from onStartCommand()
, then what is the difference between the two approaches ?
Solution
What is the difference between the two approaches ?
The method you are proposing is a wrong-headed approach, for three reasons:
- In Android,
Activity
s andService
s are considered to be app components. A component should be treated as an independent entity whose internal methods are not directly called by other components/classes. Such a component should be started using anIntent
and then left to do its own work. If you don't call
startService()
, you literally never start theService
. How then would you call a method defined inside it ? And manually creating instances of classes that are app components is frowned upon in Android. You should never do something likenew Service()
or
new Activity()
That's just bad and you're inviting a whole lot of trouble.
If you are going to call
downloadFile()
directly from yourActivity
, then why put it in aService
in the first place ? Isn't that redundant ? The reason for putting it in aService
is that the download operation is a non-UI task that requires no user interaction, which is what aService
is meant for. AnActivity
, on the other hand, is a UI-based component that is explicitly meant for user interaction. If the user dismisses yourActivity
while the download is in progress, then aNullPointerException
gets thrown when the download completes and your code tries to post the data on the UI.
Answered By - Yash Sampat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.