Robby Smet
Robby Smet

Reputation: 4661

Is this a good use case to use a service?

I have an application that listens to broadcasts and sends broadcasts.
When the application sends a broadcast it expects a broadcast back from another application.

I catch the broadcast in my receiver and then send the content to a regular java class called 'decode'. Here I check the contents of the broadcast and call a method on the mainActivity to launch another activity.

This mainActivity has no real UI, so I was thinking of making a service to replace it. So I instead of calling mainActivity from decode, I would make a service and call a method from that service.

Now , since I have no experience with android services, is this a good case to use a service ?
Where can I find a good example of android services?

Upvotes: 0

Views: 840

Answers (1)

Carnal
Carnal

Reputation: 22064

You're right, this is the time to use a Service since you should never call an Activity method from outside the Activity. I will give you the most basic Service as a template, and then you can add stuff to it as you like:

public class MyService extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override 
    public void onCreate() {
        super.onCreate();
        Log.i("daim", "MyService has started ...");
        startMyMethod();    
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("daim", "MyService has stopped ...");    
    }

    public void startMyMethod(){
        // do your work
    }
}

Now in order to start this service, you call the method startService and to stop it, call the method stopService. Now if you want to stop the service inside the service, for example when your work is done. You could call stopSelf(); inside your service method. Google for startService and stopService in order to see what parameters are needed, and how to call them depending if you are inside an Activity or not, this is where you might need the Context if you call it from inside a class.

http://developer.android.com/reference/android/app/Service.html

Upvotes: 1

Related Questions