我有一个启动服务的 Activity ,例如我将 MyService
设置为:
Intent intent1 = new Intent(this, MyService.class);
startService(intent1);
在我的服务中,我创建一个线程并运行它。这是我的代码的一部分:
public class MyService extends Service {
...
@Override
public void onStart(Intent intent, int startid) {
Thread mythread= new Thread() {
@Override
public void run() {
while(true)
{
...
}
}
};
mythread.start();
}
}
现在我想使用 while(a)
而不是 while(true)
,其中 a
是从我的此服务的 Activity 。请注意,我的 Activity 与我的服务属于不同的类别。如何才能做到这一点?请用一些代码显示具体示例。
最佳答案
您可以通过绑定(bind)来访问您的服务。编辑您的服务类,使其返回 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;
}
}
现在,在您的 Activity 中,您需要处理与服务的绑定(bind)和解除绑定(bind)。在此示例中,无论您是否受到绑定(bind),该服务都会持续存在。如果这不是您想要的功能,您可以不调用 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 );
}
}
现在您在 Activity 中拥有了对绑定(bind)服务的引用,您只需调用 myService.setA(true)
即可设置参数。
关于android - 将参数从 Activity 传递到服务中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14710765/