开发者

Android: Obtaining a class after a call to startService()

I am getting confused with all the different terminology when using Android: Activity, Service...

Right now I create a service:

startService(new Intent(this, RingerServer.class));

And this service starts a thread:

public class RingerServer extends Service {

    public void onCreate() {
        super.onCreate();

        new Thread(new Ringer()).start();
    }

    public class Ringer implements Runnable { ... }

    public void refuseConnection() { ... }

}

In this service, the RingerServer, I also 开发者_如何转开发have methods that I want to use. I would like to keep a reference to the RingerServer. I would basically like the Activity that created the service to be able to call refuseConnection(), but not make that method static.

startService returns a ComponentName, so I've been trying to cast it back to RingerServer but that doesn't seem to work. I see that it has getClass() and I've checked and getClassName() gives me the correct class. I haven't been able to use getClass() properly though.

Is there any way I can please keep a reference to the newly created RingerServer class? I am sure this is trivial, but I am stuck right now.

Thank you very much,

James


You have two options

1.Override onStartCommand of the service and start the server with intent using an action. that intent will be received in service, based on the intent action you can call refuseConnection()

//In Activity 
...
//Start the service 
Intent intent=new Intent("com.xx.xx.REFUSE_CONNECTION");
startService(this,intent);
...
//In Service 

public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if(intent.getAction().equals("com.xx.xx.REFUSE_CONNECTION")){
            //Refuse the connection
            refuseConnection();
        }else {
            //Do something else
        }
}

//In Manifest

<service android:name="RingerService">
     <intent-filter>
       <action android:name="com.xx.xx.REFUSE_CONNECTION"></action>
     </intent-filter>
</service>
  1. Implement AIDL interface and override onBind() of service , and use this interface to call refuseConnection(). Refer to this link http://developer.android.com/guide/developing/tools/aidl.html regarding AIDL.


You can use a ServiceConnection to get access to your service class. See sample code here:

Android service running after pressing Home key

That said, managing things via the service's onStart handler is much simpler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜