我的位置为空,服务已关闭

My location is null with the service turned off

提问人:Alberto Alonso Palacios 提问时间:11/17/2023 更新时间:11/17/2023 访问量:12

问:

/**

  • @file服务埃斯库哈尔信标.java
  • @brief 此文件包含用于侦听信标的服务的实现。 */

/**

  • @brief 侦听 BLE (低功耗蓝牙) 信标的服务. */ public class ServiceEscuharBeacons extends Service {

    私人双倍距离平均 = -1.0; 私有 int 样本 = 0; 私有最终 int NUM_MUESTRAS_PROMEDIO = 10; public static final String ACTION_SOLICITAR_PERMISOS_BLUETOOTH = “SOLICITAR_PERMISOS_BLUETOOTH”; public static final String ACTION_SOLICITAR_PERMISOS_UBICACION = “SOLICITAR_PERMISOS_UBICACION”; public static final int CODIGO_PETICION_PERMISO_BLUETOOTH = 1; 公共静态最终 int CODIGO_PETICION_PERMISO_UBICACION = 2;

    private Handler handler = new Handler(); 私有 PowerManager.WakeLock, mWakeLock; private Runnable getLocationRunnable; 私人静态最终双UMBRAL_CAMBIO = 2; 私有控制器BLE控制器; private 字符串 deviceSearched; 私有 int ID_AIRSENSE = 1;

    私有静态最终多头LOCATION_UPDATE_INTERVAL = 10000;10 秒间隔 私有 int ID_CO2 = 2; 通知管理器 mNotificationManager; 私有静态 int notificationId = 1;

    私有 FusedLocationProviderClient fusedLocationClient;

    @Override 公共无效 onCreate() { 超级.onCreate(); controllerBLE = new ControllerBLE(this); fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

     obtenerUbicacionRunnable = new Runnable() {
         @Override
         public void run() {
             obtenerLatitudLongitud();
             handler.postDelayed(this , LOCATION_UPDATE_INTERVAL);
         }
     };
    
     handler.postDelayed(obtenerUbicacionRunnable , LOCATION_UPDATE_INTERVAL);
    
     buscarEsteDispositivoBTLE();
    
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         NotificationChannel channel1 = new NotificationChannel("1" , "Conexion AirSense" , NotificationManager.IMPORTANCE_HIGH);
         channel1.enableVibration(true);
         channel1.setShowBadge(true);
    
         NotificationChannel channel2 = new NotificationChannel("2" , "Alertas CO2" , NotificationManager.IMPORTANCE_HIGH);
         channel2.enableVibration(true);
         channel2.setShowBadge(true);
    
         NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
         notificationManager.createNotificationChannel(channel1);
         notificationManager.createNotificationChannel(channel2);
     }
    
     // Configurar notificación persistente
     setupPersistentNotification("Has superado los limites oficiales" , "Nivel alto de CO2" , "2" , ID_CO2);
    

    }

    private void setupPersistentNotification(字符串标题 , 字符串文本 , 字符串通道 , int id) { 通知通知 = createNotification(title, text, channel, id); 通知可见性 = Notification.VISIBILITY_PUBLIC;

     // Modificación aquí
     startForeground(id , notification);
    

    }

    private void showNotification(通知通知,int id) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(id , 通知);

    }

    私有 void 搜索 ThisDeviceBTLE() { BLEdriver.searchThisBTLEDevice(deviceWanted, new BLECallback() { @Override public void onSuccess(String valor_medicion , String id_medicion , 字符串名称 , double Rssi , double txpower) { double distance = Double.parseDouble(String.valueOf(calculateDistance(txpower , Rssi , 2))); double distanceAverage = calculateAverage(距离);

             if (distanciaPromedio < 0 || Math.abs(distancia - distanciaPromedio) < UMBRAL_CAMBIO) {
    
    
                 Intent intent = new Intent("airsense-conectado");
                 intent.putExtra("distancia" , String.format("%.2f" , distanciaPromedio));
                 intent.putExtra("valor_medicion" , valor_medicion);
                 intent.putExtra("id_medicion" , id_medicion);
                 LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
             }
         }
     });
    

    }

    公共无效 getLatitudeLongitude() { if (ActivityCompat.checkSelfPermission(this , android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this , Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 返回; }

     fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY , null)
             .addOnSuccessListener(TaskExecutors.MAIN_THREAD , new OnSuccessListener<Location>() {
                 @Override
                 public void onSuccess(Location location) {
                     if (location != null) {
                         double latitud = location.getLatitude();
                         double longitud = location.getLongitude();
    
                         Intent latitud1 = new Intent("LATITUD");
                         latitud1.putExtra("latitud" , latitud);
                         latitud1.putExtra("longitud" , longitud);
                         LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(latitud1);
                     } else {
                         Log.e("MiServicio" , "Ubicación nula");
                         Toast.makeText(getApplicationContext() , "Ubicación nula" , Toast.LENGTH_SHORT).show();
                     }
                 }
             })
             .addOnFailureListener(new OnFailureListener() {
                 @Override
                 public void onFailure(@NonNull Exception e) {
                     // Manejar fallo al obtener la ubicación
                     Toast.makeText(getApplicationContext() , "Error al obtener la ubicación" , Toast.LENGTH_SHORT).show();
                     e.printStackTrace();
                 }
             });
    

    }

    @SuppressLint(“InvalidWakeLockTag”) @Override public int onStartCommand(意图意图 , int 标志 , int startId) { if (intent != null) { 字符串操作 = intent.getAction(); if (“deviceWanted”.equals(action)) { if (intent.getStringExtra(“deviceSearched”) != null) { 字符串 deviceSearched = intent.getStringExtra(“deviceSearched”); this.deviceSearched = 设备搜索; }

             // Adquirir WakeLock
             PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
             if (this.mWakeLock == null) {
                 this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK , "MyWakeLock");
             }
             if (!this.mWakeLock.isHeld()) {
                 this.mWakeLock.acquire();
             }
    
             obtenerLatitudLongitud();
             buscarEsteDispositivoBTLE();
             controladorBLE.detenerBusquedaDispositivosBTLE();
         }
     }
    
     return Service.START_STICKY;
    

    }

    @Override 公共无效 onDestroy() { handler.removeCallbacks(getRunnable 位置); 控制器BLE.stopSearchDevicesBTLE();

     NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
     notificationManager.cancel(1);
    
     // Liberar WakeLock
     if (this.mWakeLock != null) {
         if (this.mWakeLock.isHeld()) {
             this.mWakeLock.release();
         }
         this.mWakeLock = null;
     }
    
    
     super.onDestroy();
    

    }

    @Nullable @Override public IBinder onBind(Intent intent) { 返回 null; }

    /**

    • @param title 通知的标题。
    • @return 已创建的通知。
    • @brief 为服务创建通知。 */

    private 通知 createNotification(String title, String text, String channel, int id) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this , channel) .setSmallIcon(R.drawable.logo) .setContentTitle(标题) .setContentText(文本) .setPriority(NotificationCompat.PRIORITY_MAX) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setColor(颜色.rgb(49, 143, 169)) .setOngoing(假);

     Intent notificationIntent = new Intent(this , Home.class);
     PendingIntent pendingIntent;
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
         pendingIntent = PendingIntent.getService(this , id , notificationIntent , PendingIntent.FLAG_IMMUTABLE);
     } else {
         pendingIntent = PendingIntent.getService(this , id , notificationIntent , PendingIntent.FLAG_IMMUTABLE);
     }
     builder.setContentIntent(pendingIntent);
    
     return builder.build();
    

    }

    /**

    • @brief 使用新消息更新通知。 */ /private void updateNotification(字符串标题,int id) { 通知通知 = createNotification(title, id); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(id , 通知); }/

    /**

    • @param txPower 已知发射功率。
    • @param rssi 接收信号的强度。
    • @param n 环境校正系数。
    • @return 以米为单位计算的距离。
    • @brief 使用信号强度和接收信号强度 (RSSI) 计算两个设备之间的距离。 */ 私有 double calculateDistance(double txPower , double rssi , double n) { 如果 (rssi == 0) { 返回 -1.0;无效值 } 返回 Math.pow(10 , ((txPower - rssi) / (10 * n))); }

    /**

    • @param新样本 样本的新值。
    • @return 计算出的移动平均线。
    • @brief 计算最新样本的移动平均线 */ 私有双 calculateAverage(double newSample) { 如果(< NUM_MUESTRAS_PROMEDIO个样本){ 还没有积累足够的样本,只需将旧样本和新样本相加即可 distanceAverage = (distanceAverage * 样本 + newSample) / (样本 + 1); 示例++; } else { 如果积累了足够的样本,则通过删除最旧的样本来计算移动平均值 distanceAverage = distanceAverage + (newSample - distanceAverage) / NUM_MUESTRAS_PROMEDIO; } 返回距离平均; } }
Android 服务本地化地理位置

评论


答: 暂无答案