ble后台广告

kpbwa7wx  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(200)

我´我在一个联系人追踪项目的android应用程序里工作。我现在需要的是做一个后台进程(idk if、服务、前台服务、worker等等),这样即使应用程序关闭,也可以保持ble广告客户发送信标。在主线程上没有问题,但是当我尝试在服务中转换时,它可以´我不能开始。这是我尝试的服务类:

public class AdvertiserService extends Service {
    private  BluetoothLeAdvertiser advertiser;
    private  AdvertiseSettings settings;
    private  AdvertiseCallback callback;

  @Override
  public void onCreate() {
      super.onCreate();
      advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();

      settings = new AdvertiseSettings.Builder()
              .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
              .setConnectable(false)
              .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
              .setTimeout(0)
              .build();

      callback = new AdvertiseCallback() {
          @Override
          public void onStartSuccess(AdvertiseSettings settingsInEffect) {
              super.onStartSuccess(settingsInEffect);
          }

          @Override
          public void onStartFailure(int errorCode) {
              super.onStartFailure(errorCode);
          }
      };
 }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
     long userId = 
Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this)
              .getString(getString(R.string.user_id_pref_key), "0"));
      MeetingBeacon beacon = new MeetingBeacon(userId, userId);
      Log.d("MEETING_BACON", beacon.getBeaconUUID().toString() );
      AdvertiseData data = new AdvertiseData.Builder()
              .addServiceData(beacon.getBeaconUUID(), beacon.getBeaconData())
              .build();
      advertiser.startAdvertising(settings, data, callback);
     return START_STICKY;
  }

  @Override
  public void onDestroy(){
      Log.d("ADVER-Sv","Automate service destroyed...");
      advertiser.stopAdvertising(callback);
      super.onDestroy();
  }

  @Override
  public IBinder onBind(Intent intent) {
      return null;
  }

  @Override
  public boolean stopService(Intent name) {
      Log.d("SCAN-Sv","Automate service stop...");
      advertiser.stopAdvertising(callback);
      stopSelf();
      return super.stopService(name);
 }
}

我呢´我将从主线程启动此服务:

advertiserService = new Intent(this, AdvertiserService.class);

    if(advertiserEnabled) {
        ComponentName ret = startService(advertiserService);
        if(ret != null){
            Log.d("SERVICE:", sv.toString());
        }
        Log.d("SERVICE ", "fail");
    }

但是ret总是空的,所以服务不能启动。在这种情况下,idk if使用服务是更好的解决方案。有谁能提出解决这个问题的更好办法吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题