簡體   English   中英

服務方法在onCreate方法中僅執行一次

[英]Service method is executed only once in onCreate method

我有一個ForegroundService類,從另一個活動中我的onStartCommand()方法上獲得了Extras。僅當我第一次啟動服務時, startScanning()執行startScanning()方法。 第二次及之后,我的方法沒有執行。如何解決該問題? 盡管我的IBeaconRegion對象的集合已更新,但是我的集合中的第二項未包含在我的startScanning方法中。我希望我的startScanning方法( onRegionEnteredonRegionAbandoned )能夠連續執行,包括集合中添加的每個新對象。 第一個Region對象包含在onRegionEntered中 第二區域對象包含在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);
  }


}

這段代碼在到達方法末尾之前完成了onStartCommand()的執行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM