服务方法仅在onCreate方法

时间:2018-04-09 12:02:53

标签: android service

我有一个ForegroundService类,我从另一个活动获取onStartCommand()方法的额外内容。只有当我第一次启动我的服务时,才会执行startScanning()方法。第二次及以后,我的方法没有执行..我该如何解决?尽管我的IBeaconRegion对象集合已更新,但我的startScanning方法中未包含我的第二个项目..我想要startScanning方法onRegionEntered & onRegionAbandoned)连续执行,包括在集合中添加的每个新对象。 First Region Object is included to onRegionEnteredSecond Region Object is not included to onRegionEntered。任何解决方案?

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);
  }


}

1 个答案:

答案 0 :(得分:0)

这段代码在到达方法结束之前完成onStartCommand()的执行:

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