简体   繁体   中英

Service method is executed only once in onCreate method

I have a ForegroundService class where I get Extras on my onStartCommand() method from another activity.. Only when I start my service for the first time, the startScanning() method is executed. The second time and after, my method isn't executed.. How can I fix that? Despite the fact that my collection of IBeaconRegion objects is updated, the second item of my collection is not included in my startScanning method.. I want my startScanning method ( onRegionEntered & onRegionAbandoned ) to be executed continuously, including every new object added in the collection. First Region Object is included to onRegionEntered . Second Region Object is not included to onRegionEntered . Any solutions?

public class ForegroundScanService extends Service {

  public static final String TAG = ForegroundScanService.class.getSimpleName();

  public static final String ACTION_DEVICE_DISCOVERED = "DEVICE_DISCOVERED_ACTION";
  public static final String EXTRA_DEVICE = "DeviceExtra";
  public static final String EXTRA_DEVICES_COUNT = "DevicesCountExtra";

  private static final String STOP_SERVICE_ACTION = "STOP_SERVICE_ACTION";

  private static final String NOTIFICATION_CHANEL_NAME = "Kontakt SDK Samples";
  private static final String NOTIFICATION_CHANEL_ID = "scanning_service_channel_id";

  private ProximityManager proximityManager;

  private boolean isRunning; // Flag indicating if service is already running.
  private int devicesCount; // Total discovered devices count
  private Collection<IBeaconRegion> homeRegions = new ArrayList<>();
  private IBeaconRegion homeRegion;

  public static Intent createIntent(final Context context) {
    return new Intent(context, ForegroundScanService.class);
  }

  @Override
  public void onCreate() {
    super.onCreate();
    setupProximityManager();

    isRunning = false;
  }

  private void setupProximityManager() {
    // Create proximity manager instance
    proximityManager = ProximityManagerFactory.create(this);

    // Configure proximity manager basic options
    proximityManager.configuration()
        //Using ranging for continuous scanning or MONITORING for scanning with intervals
        .scanPeriod(ScanPeriod.RANGING)
        //Using BALANCED for best performance/battery ratio
        .scanMode(ScanMode.BALANCED);

    // Set up iBeacon listener
    proximityManager.setIBeaconListener(new SimpleIBeaconListener() {
    });
    //Setting up iBeacon and Eddystone spaces listeners
    proximityManager.setSpaceListener(createSpaceListener());

  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    //GET REGION_NAME AND BEACON_MAJOR FROM NEW REGION ACTIVITY...
    String regionGet = intent.getStringExtra("region_name");
    int majorGet = intent.getIntExtra("beacon_major", 0);
    Toast.makeText(ForegroundScanService.this, "Name passed: " + regionGet + "Major passed: " + majorGet, Toast.LENGTH_SHORT).show();
    Log.d(TAG,"Region_Name: " + regionGet);
    Log.d(TAG,"Major: " + majorGet);



      if (regionGet != null && majorGet != 0) {
          homeRegion = new BeaconRegion.Builder()
                  .identifier(regionGet)
                  .proximity(UUID.fromString("f7826da6-4fa2-4e98-8024-bc5b71e0893e"))
                  .major(majorGet)
                  .build();
          homeRegions.add(homeRegion);

          proximityManager.spaces()
                  .iBeaconRegions(homeRegions);
        Log.d(TAG, "Region ADDED" + "COLLECTION SIZE IS: " + homeRegions.size());
      }



    if (STOP_SERVICE_ACTION.equals(intent.getAction())) {
      stopSelf();
      return START_NOT_STICKY;
    }

    // Check if service is already active
    if (isRunning) {
      Toast.makeText(this, "Service is already running.", Toast.LENGTH_SHORT).show();
      return START_STICKY;
    }

    startInForeground();
    startScanning();
    isRunning = true;



    return START_STICKY;
  }

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

  @Override
  public void onDestroy() {
    if (proximityManager != null) {
      proximityManager.disconnect();
      proximityManager = null;
    }
    Toast.makeText(this, "Scanning service stopped.", Toast.LENGTH_SHORT).show();
    super.onDestroy();
  }

  private void startInForeground() {
    // Create notification intent
    final Intent notificationIntent = new Intent();
    final PendingIntent pendingIntent = PendingIntent.getActivity(
        this,
        0,
        notificationIntent,
        0
    );

    // Create stop intent with action
    final Intent intent = ForegroundScanService.createIntent(this);
    intent.setAction(STOP_SERVICE_ACTION);
    final PendingIntent stopIntent = PendingIntent.getService(
        this,
        0,
        intent,
        PendingIntent.FLAG_CANCEL_CURRENT
    );

    // Create notification channel
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      createNotificationChannel();
    }

    // Build notification
    final NotificationCompat.Action action = new NotificationCompat.Action(0, "Stop", stopIntent);
    final Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANEL_ID)
        .setContentTitle("Scan service is Active")
        .setContentText("Scanning for IBeacons Regions")
        .addAction(action)
        .setSmallIcon(android.R.drawable.ic_dialog_email)
        .setContentIntent(pendingIntent)
        .build();

    // Start foreground service
    startForeground(1, notification);
  }

  @RequiresApi(api = Build.VERSION_CODES.O)
  private void createNotificationChannel() {
    final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (notificationManager == null) return;

    final NotificationChannel channel = new NotificationChannel(
        NOTIFICATION_CHANEL_ID,
        NOTIFICATION_CHANEL_NAME,
        NotificationManager.IMPORTANCE_DEFAULT
    );
    notificationManager.createNotificationChannel(channel);
  }

  private void startScanning() {
    proximityManager.connect(new OnServiceReadyListener() {
      @Override
      public void onServiceReady() {
        proximityManager.startScanning();
        devicesCount = 0;
        Toast.makeText(ForegroundScanService.this, "Scanning service started.", Toast.LENGTH_SHORT).show();
      }
    });
  }

  private SpaceListener createSpaceListener() {
    return new SpaceListener() {
      @Override
      public void onRegionEntered(IBeaconRegion region) {
        Log.i(TAG, "New Region entered: " + region.getIdentifier());
      }

      @Override
      public void onRegionAbandoned(IBeaconRegion region) {
        Log.e(TAG, "Region abandoned " + region.getIdentifier());
      }

      @Override
      public void onNamespaceEntered(IEddystoneNamespace namespace) {
        Log.i(TAG, "New Namespace entered: " + namespace.getIdentifier());
      }

      @Override
      public void onNamespaceAbandoned(IEddystoneNamespace namespace) {
        Log.i(TAG, "Namespace abandoned: " + namespace.getIdentifier());
      }
    };
  }

  private void onDeviceDiscovered(final RemoteBluetoothDevice device) {
    devicesCount++;
    //Send a broadcast with discovered device
    Intent intent = new Intent();
    intent.setAction(ACTION_DEVICE_DISCOVERED);
    intent.putExtra(EXTRA_DEVICE, device);
    intent.putExtra(EXTRA_DEVICES_COUNT, devicesCount);
    sendBroadcast(intent);
  }


}

This piece of code completes the execution of onStartCommand() before it reaches the end of the method:

// Check if service is already active
if (isRunning) {
  Toast.makeText(this, "Service is already running.", Toast.LENGTH_SHORT).show();
  return START_STICKY;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM