开发者

how to reference object created with Intent / startService

If I create a service in my app'开发者_如何学Gos onCreatelike this:

Intent srv = new Intent( this, MyService.class );
startService( srv );

how do I get a reference to the service object and how does the service object reference the app which launched it?

(Yes, I have listed the service in my AndroidManifest).


There are a few ways to handle this. You can bind to the service (bindService) where you will be called back with an IBinder interface.

Another approach is to just keep calling startService() with different intent data as a way of messaging to the service, with intent extra data containing message specifics.

Finally, if you know the service is in the same process, you can share the service instance in some static memory.


Building a Service

First of all, we need to create the Service in the AndroidManifest.xml file. Remember, that every Activity, Service, Content Provider you create in the code, you need to create a reference for here, in the Manifest, if not, the application will not recognize it.

<service android:name=".subpackagename.ServiceName"/>

In the code, we need to create a class that extends from “Service”

public class ServiceName extends Service {

    private Timer timer = new Timer();

    protected void onCreate() {

        super.onCreate();

        startservice();

    }

}

This is a way to create Services, there are others ways, or the way I use to work with them. Here, we create a Timer, that every X seconds, calls to a method. This is running until we stop it. This can be used, for example, to check updates in an RSS feed. The “Timer” class is used in the startservice method like this

private void startservice() {

    timer.scheduleAtFixedRate( new TimerTask() {

    public void run() {

        //Do whatever you want to do every “INTERVAL”

    }

    }, 0, INTERVAL);

; }

Where INTERVAL, is the time, every time the run method is executed.

To stop the service, we can stop the timer, for example, when the application is destroyed (in onDestroy())

private void stopservice() {

    if (timer != null){

    timer.cancel();

    }

}

So, this application will be running in the background...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜