Android 从后台服务中估计信标区域检测

Android 从后台服务中估计信标区域检测,android,ibeacon,ibeacon-android,estimote,Android,Ibeacon,Ibeacon Android,Estimote,我最近开始测试Estimote信标,并尝试在进入信标区域时从后台服务启动通知,但不幸的是,我的解决方案不起作用。它不会给出错误,但在发现信标时不会启动通知。我不知道这是否是一些代码错误,或者仅仅是这样做的方式是错误的。我读过另一个问题,但它似乎有点不同,因为我使用的是服务而不是活动,但可能答案是类似的(应用程序上下文相关) 这是我的服务代码 public class BeaconsMonitoringService extends Service{ private BeaconMana

我最近开始测试Estimote信标,并尝试在进入信标区域时从后台服务启动通知,但不幸的是,我的解决方案不起作用。它不会给出错误,但在发现信标时不会启动通知。我不知道这是否是一些代码错误,或者仅仅是这样做的方式是错误的。我读过另一个问题,但它似乎有点不同,因为我使用的是服务而不是活动,但可能答案是类似的(应用程序上下文相关)

这是我的服务代码

public class BeaconsMonitoringService extends Service{

    private BeaconManager beaconManager;

    private String user;

    @Override
      public void onCreate() {
        // Configure BeaconManager.
        beaconManager = new BeaconManager(this);

      }

      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          Toast.makeText(this, "Beacons monitoring service starting", Toast.LENGTH_SHORT).show();

          user = intent.getStringExtra("user");

            // Check if device supports Bluetooth Low Energy.
            if (!beaconManager.hasBluetooth()||!beaconManager.isBluetoothEnabled()) {
              Toast.makeText(this, "Device does not have Bluetooth Low Energy or it is not enabled", Toast.LENGTH_LONG).show();
              this.stopSelf();
            }

              connectToService();


          // If we get killed, after returning from here, restart
          return START_STICKY;
      }

      @Override
      public IBinder onBind(Intent intent) {
          // We don't provide binding, so return null
          return null;
      }

      @Override
      public void onDestroy() {
        Toast.makeText(this, "Beacons monitoring service done", Toast.LENGTH_SHORT).show();
      }

      private void connectToService() {


          beaconManager.connect(new BeaconManager.ServiceReadyCallback() {

            @Override
            public void onServiceReady() {
                notifyEnterRegion(0);
//            try {
                  beaconManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
                  Log.i("BEACOON ", "ANTES DE");
                  beaconManager.setMonitoringListener(new MonitoringListener() {
                    @Override
                    public void onEnteredRegion(Region region, List<Beacon> beacons) {
                      Log.i("BEACOON ", String.valueOf(beacons.get(1).getMinor()));
                    for (Beacon beacon: beacons){
                        Log.i("BEACOON ", String.valueOf(beacon.getMinor()));
                        if (beacon.getMinor() == 64444) {

                            notifyEnterRegion(6444);

                        } else if (beacon.getMinor() == 36328) {

                            notifyEnterRegion(36328);

                        } else if (beacon.getMinor() == 31394) {

                            notifyEnterRegion(31394);

                        }
                    }
                    }

                    @Override
                    public void onExitedRegion(Region region) {

                        notifyExitRegion();

                    }
                  });  

            }
          });
        }

      public void notifyEnterRegion(int code) {

            Toast.makeText(this, "Beacon "+code, Toast.LENGTH_SHORT).show();

            Intent targetIntent = new Intent(this, MainActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            Notification noti = new Notification.Builder(this)
             .setContentTitle("Bienvenido "+user+"!")
             .setContentText("Sólo por estar aquí has ganado....")
             .setSmallIcon(com.smt.beaconssmt.R.drawable.beacon_gray)
             .setContentIntent(contentIntent)
             .getNotification();

            NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            nManager.notify(1, noti);
        }

      public void notifyExitRegion(){

            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setMessage("Hasta pronto!")
                   .setTitle(user+", estás abandonando la zona de beacons");

            builder.setPositiveButton("Ver web", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           // User clicked OK button
                           Intent i = new Intent(BeaconsMonitoringService.this, WebViewActivity.class);
                           i.putExtra("web", "http://www.google.com/");
                           startActivity(i);
                       }
                   });
            builder.setNegativeButton("Adios!", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           // User cancelled the dialog
                       }
                   });

            AlertDialog dialog = builder.create();

            dialog.show();
      }



}
公共类beaconMonitoringService扩展服务{
私人BeaconManager BeaconManager;
私有字符串用户;
@凌驾
public void onCreate(){
//配置BeaconManager。
beaconManager=新的beaconManager(此);
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
Toast.makeText(这是“信标监控服务启动”,Toast.LENGTH_SHORT.show();
user=intent.getStringExtra(“用户”);
//检查设备是否支持蓝牙低能量。
如果(!beaconManager.hasBluetooth()| |!beaconManager.IsBluetooth已启用()){
Toast.makeText(此“设备没有蓝牙低能量或未启用”,Toast.LENGTH_LONG.show();
这个。stopSelf();
}
connectToService();
//如果我们被杀了,从这里回来后,重新开始
返回开始时间;
}
@凌驾
公共IBinder onBind(意向){
//我们不提供绑定,所以返回null
返回null;
}
@凌驾
公共空间{
Toast.makeText(这是“信标监控服务完成”,Toast.LENGTH_SHORT.show();
}
私有void connectToService(){
connect(新的beaconManager.ServiceReadyCallback(){
@凌驾
服务日上的公共无效(){
区域(0);
//试一试{
beaconManager.setBackgroundScanPeriod(时间单位为秒,单位为1,0);
Log.i(“BEACOON”、“ANTES DE”);
beaconManager.setMonitoringListener(新建MonitoringListener(){
@凌驾
公共区域(区域、列表信标){
Log.i(“BEACOON”,String.valueOf(beacons.get(1.getMinor()));
用于(信标:信标){
Log.i(“BEACOON”,String.valueOf(beacon.getMinor());
if(beacon.getMinor()==64444){
新界北总区(6444);
}else if(beacon.getMinor()==36328){
亚洲区(36328);
}else if(beacon.getMinor()==31394){
新界北总区(31394);
}
}
}
@凌驾
公共无效onExitedRegion(区域){
notifyExitRegion();
}
});  
}
});
}
公共区域(内部代码){
Toast.makeText(这个“信标”+代码,Toast.LENGTH_SHORT).show();
Intent targetIntent=新的Intent(此,MainActivity.class);
PendingEvent contentIntent=PendingEvent.getActivity(this,0,targetEvent,PendingEvent.FLAG_UPDATE_CURRENT);
Notification noti=新建Notification.Builder(此)
.setContentTitle(“Bienvenido”+用户+“!”)
.setContentText(“Sólo por estar aqíhas ganado….”)
.setSmallIcon(com.smt.beaconssmt.R.drawable.beacon_gray)
.setContentIntent(contentIntent)
.getNotification();
NotificationManager nManager=(NotificationManager)getSystemService(Context.NOTIFICATION_服务);
n管理者通知(1,noti);
}
公共无效通知exitregion(){
AlertDialog.Builder=新建AlertDialog.Builder(此);
setMessage(“hastapronto!”)
.setTitle(用户+”,estás Aboutando la zona de beacons”);
setPositiveButton(“Ver web”,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int-id){
//用户单击“确定”按钮
意图i=新意图(beaconMonitoringService.this、WebViewActivity.class);
i、 putExtra(“网络”http://www.google.com/");
星触觉(i);
}
});
setNegativeButton(“Adios!”,新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int-id){
//用户取消了该对话框
}
});
AlertDialog=builder.create();
dialog.show();
}
}

我将非常感谢任何帮助,提前谢谢!

此代码对我有效。请确保您放置了正确的UUID、次要和主要编号

//Using something like that as global variable

    private static final Region[] BEACONS = new Region[] { 
    new Region("beacon1", "uuid1", 1, 19227), //uuid without "-"
    new Region("beacon2", "uuid2", 1, 61690),
    new Region("beacon3", "uuid3", null, null)
};
//Note: setting minor == null and major == null will detect every beacon with that uuid

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      startMonitoring();
      return START_STICKY;
  }



private void startMonitoring() {
    if (beaconManager == null) {
        beaconManager = new BeaconManager(this);

        // Configure verbose debug logging.
        L.enableDebugLogging(true);

        /**
         * Scanning
         */
        beaconManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 1);

        beaconManager.setRangingListener(new RangingListener() {

            @Override
            public void onBeaconsDiscovered(Region paramRegion, List<Beacon> paramList) {
                if (paramList != null && !paramList.isEmpty()) {
                    Beacon beacon = paramList.get(0);
                    Proximity proximity = Utils.computeProximity(beacon);
                    if (proximity == Proximity.IMMEDIATE) {
                        Log.d(TAG, "entered in region " + paramRegion.getProximityUUID());
                        postNotification(paramRegion);
                    } else if (proximity == Proximity.FAR) {
                        Log.d(TAG, "exiting in region " + paramRegion.getProximityUUID());
                         removeNotification(paramRegion);
                    }
                }
            }

        });

        beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
            @Override
            public void onServiceReady() {
                try {
                    Log.d(TAG, "connected");
                    for (Region region : BEACONS) {
                        beaconManager.startRanging(region);
                    }
                } catch (RemoteException e) {
                    Log.d("TAG", "Error while starting monitoring");
                }
            }
        });
    }
}
//使用类似的内容作为全局变量
专用静态最终区域[]信标=新区域[]{
新区域(“beacon1”、“uuid1”、119227),//uuid不带“-”
新区域(“beacon2”、“uuid2”、161690),
新区域(“beacon3”、“uuid3”、空、空)
};
//注意:设置minor==null和major==null将检测具有该uuid的每个信标
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
开始监视();
返回开始时间;
}
私有无效开始监视(){
如果(beaconManager==null){
beaconManager=新的beaconManager(此)
 public static double computeAccuracy(Beacon beacon)
 {
    if (beacon.getRssi() == 0) 
    {
       return -1.0D;
    }

    double ratio = beacon.getRssi() / beacon.getMeasuredPower();
    double rssiCorrection = 0.96D + Math.pow(Math.abs(beacon.getRssi()), 3.0D) % 10.0D / 150.0D;

    if (ratio <= 1.0D) 
    {
       return Math.pow(ratio, 9.98D) * rssiCorrection;
    }
    return (0.103D + 0.89978D * Math.pow(ratio, 7.71D)) * rssiCorrection;
 }

 public static Proximity proximityFromAccuracy(double accuracy)
 {
    if (accuracy < 0.0D) 
    {
        return Proximity.UNKNOWN;
    }
    if (accuracy < 0.5D) 
    {
        return Proximity.IMMEDIATE;
    }
    if (accuracy <= 3.0D) {
        return Proximity.NEAR;
    }
    return Proximity.FAR;
}



 public static Proximity computeProximity(Beacon beacon) {
     return proximityFromAccuracy(computeAccuracy(beacon));
 }
beaconManager.setRangingListener(new BeaconManager.RangingListener() {

        @Override
        public void onBeaconsDiscovered(Region region, final List<Beacon> beaconList) {
            if (!beaconList.isEmpty()) {
                Beacon nearestBeacon = beaconList.get(0);
                Log.e("Current Proximity - ", String.valueOf(Utils.computeProximity(nearestBeacon)));
            }
        }
});