java如何等待服务绑定?
我正在为我的应用程序编程蓝牙服务。我对安卓系统的服务知之甚少,但我设法启动了一个,并以我想要的方式使用它
当我试图在Activity的onCreate()
方法上使用服务中的函数时,我的问题就出现了(它没有足够的时间绑定服务)
我将代码结构化为3个类:
蓝牙服务: 实现该服务的类
public class BluetoothService extends Service implements IScanService { private final IBinder bluetoothBinder = new BluetoothBinder(); @Override public IBinder onBind(Intent intent) { return bluetoothBinder; } public class BluetoothBinder extends Binder { public BluetoothService getService() { return BluetoothService.this; } } // Other functions }
蓝牙活动: 处理蓝牙服务连接的抽象类(用于重用)
public abstract class BluetoothActivity extends AppCompatActivity { protected BluetoothService bluetoothService; protected volatile Boolean isBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Connecting to the service Intent intent = new Intent(this, BluetoothService.class); bindService(intent, connection, Context.BIND_AUTO_CREATE); } private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { BluetoothService.BluetoothBinder binder = (BluetoothService.BluetoothBinder) service; bluetoothService = binder.getService(); isBound = true; } @Override public void onServiceDisconnected(ComponentName className) { isBound = false; } }; // Other functions }
扫描活动: 从BluetoothActivity扩展并在“onCreate()”上使用BluetoothService方法的Activity类
变量“isBound”用于了解服务是否已绑定(或者是否必须等待)
我尝试的是:
- 使用“wait()”和“notify()”但对我无效李>
- 使用“while(!isBound)”等待,但应用程序刚刚崩溃李>
- 使用处理程序等待x毫秒。这是有效的,但我知道不是这样,因为服务可能不受约束李>
因此,我的问题是如何等待'onCreate()'方法,直到'isBound'变为真
# 1 楼答案
我刚刚意识到我可以在
BluetoothService
上创建两个函数,并在onServiceConnected()
和onServiceDisconnected()
上调用它们:然后在扩展类上重写它们: