我正在使用Alt信标库进行信标扫描。我在服务班扫描信标。我想继续扫描信标,即使应用程序也关闭了。但如果关闭,应用程序服务停止,信标不扫描。我试过了,但是我没有。请帮助我,谢谢
//MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MainActivity.this, ScaningService.class);
startService(intent);//starting service
getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);//bounding service
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
//服务类
public class ScaningService extends Service implements BeaconConsumer {
public BeaconManager beaconManager;
public MainActivity activity;
private final IBinder mBinder = new SimpleServiceBinder();
public class SimpleServiceBinder extends Binder {
public ScaningService getService() {
return ScaningService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
handler = new Handler();
beaconManager = BeaconManager.getInstanceForApplication(getBaseContext());
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.setBackgroundMode(true);
beaconManager.setBackgroundScanPeriod(1100);//this will set how long a bluetooth should scan
beaconManager.setBackgroundBetweenScanPeriod(2000);//this will set bluetooth scanning interval
beaconManager.bind(ScaningService.this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
@Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
beacon = beacons.iterator().next();
Log.e(TAG, " UUID: " + beacon.getId1());// this is not showing and i tried toast also
}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("sBeacon", null, null, null));
} catch (RemoteException e) {
Log.i(TAG, "RemoteException: " + e);
}
}
}
是的,这是可能的。如果配置得当,Android Beacon Library会在你的应用被关闭后5分钟内在后台恢复扫描。在范围回调中,您可以将数据与扫描结果一起发送到服务器,尽管您可能需要在新线程(使用Handler
或类似结构)上这样做。
上面的项目网站上的例子应该能让你大致了解。您将需要在自定义Application
类中组合背景启动和范围。
EDIT:看到发布的代码后,很明显问题是扫描是从自定义服务触发的。虽然这可以工作,但要让它正常工作要困难得多,所以扫描重新启动被杀死的应用程序。遵循使用RegionBootstrap
触发使用自定义Application
类的背景检测的示例要简单得多。