我正在使用后台服务和活动进行扫描。因此,当后台服务和活动都并行运行时,扫描时不会给出任何信标。所以当扫描活动打开时我停止服务然后它给出了#34;无法联系服务来设置扫描周期"错误。之后扫描停止活动
答案 0 :(得分:0)
我首先使用相同的设置 - 前景活动和后台服务,两者都与BLE外围设备通信。
但后来我重写了我的活动只是为了与服务沟通 - 只有后者与BLE外围设备进行通信:
public class MainActivity extends Activity {
private Intent mServiceIntent;
private ScanService mService;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
ScanBinder sb = (ScanBinder) binder;
mService = sb.getService();
mService.setActivity(MainActivity.this);
Utils.showToast(MainActivity.this, "Connected to service");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Utils.showToast(MainActivity.this, "Disconnected from service");
mService.setActivity(null);
mService = null;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mServiceIntent = new Intent(this, ScanService.class);
startService(mServiceIntent);
......
public class ScanService extends Service {
private Activity mActivity;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mActivity != null)
Utils.showToast(this, "Service (re)started");
return START_STICKY;
}
public void setActivity(Activity activity) {
mActivity = activity;
}
这种沟通在Lars Vogel的9. Exercise: Define and consume local service教程中有所描述。