您可以通过绑定来访问您的服务。编辑您的服务类,使其返回一个 IBinder onBind()
public class MyService extends Service {
private static final String TAG = MyService.class.getSimpleName();
private final IBinder binder = new ServiceBinder();
private boolean a;
@Override
public IBinder onBind( Intent intent ) {
return binder;
}
@Override
public int onStartCommand( Intent intent, int flags, int startId ) {
return super.onStartCommand( intent, flags, startId );
}
@Override
public void onCreate() {
super.onCreate();
}
public class ServiceBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
public void setA(boolean a) {
this.a = a;
}
}
现在在您的活动中,您需要处理与服务的绑定和解除绑定。在此示例中,无论您是否绑定,该服务都会一直存在。如果这不是您想要的功能,您可以不调用startService(...)
:
public class MyActivity extends Activity {
//...
private MyService myService;
private boolean bound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent( this, MyService.class );
startService( intent );
doBindService();
}
private final ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected( ComponentName className, IBinder service ) {
myService = ( (MyService.ServiceBinder) service ).getService();
bound = true;
}
public void onServiceDisconnected( ComponentName className ) {
myService = null;
bound = false;
}
};
void doBindService() {
boolean bound = bindService( new Intent( this, MyService.class ), serviceConnection, Context.BIND_AUTO_CREATE );
if ( bound ) {
Log.d( TAG, "Successfully bound to service" );
}
else {
Log.d( TAG, "Failed to bind service" );
}
}
void doUnbindService() {
unbindService( serviceConnection );
}
}
现在您在活动中引用了绑定服务,您只需调用myService.setA(true)
即可设置参数。