Как остановить Сервис в Android Wear OS - PullRequest
0 голосов
/ 02 апреля 2020

Я создаю приложение smartwatch в Android. В этом приложении есть служба, подобная этой:

public class ZeplyrServiceSweetblue extends Service/*IntentService*/ implements ZephyrListener {
    private static final int ZEPHYR_SERVICE_ID = 200;
    public static boolean isStarted = false;
    private boolean isRecording = true;
    private List<ZephyrDataRequest.DataBean> zephyrDataList;
    private ZephyrDataRequest zephyrDataRequest;
    private String macaddress;
    private String zephyrTimeString;
    private long zephyerScanningTime;
    private boolean isSopStarted = false;
    private ZephyrHelper mZephyrHelper;
    private List<EcgParcelPacket> ecgValueRequestList;
    private ECGMqttParcel mqttParcel;
    private List<ZephyrDataRequest.ECGDataBean> ecgDataList = null;
    private List<RRRequest.RrDataBean> rrDataList = null;
    private ArrayList<Double> ecgList;
    private RRRequest rrDataRequest = new RRRequest();
    private List<HRVRequest.HrvDataBean> hrvDataList = new ArrayList<>();
    private HRVRequest hrvDataRequest = new HRVRequest();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MICHELE", "onCreate");
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        Log.i("Zephyr", "onStartCommand");
        Log.i("MICHELE", "onStartCommand");
        return START_NOT_STICKY;
    }

    /**
     * Disconnect zephyr module
     */
    private void disconnectZephyr() {
        Log.i("Zephyr", "disconnectZephyr");
        Log.i("MICHELE", "disconnectZephyr");
    }

    @Override
    public void onDeviceConnected(BleDevice device) {
        Log.i("Zephyr", "onDeviceConnected");
        Log.i("MICHELE", "onDeviceConnected");
        isRecording = true;
    }

    @Override
    public void onDeviceNotFound() {
        Log.i("MICHELE", "onDeviceNotFound");
        if (!isSopStarted && zephyerScanningTime != 0) {
            isSopStarted = true;
            new Handler(getMainLooper()).postDelayed(this::disconnectZephyr, 1000);
        }
    }

    @Override
    public void onError(String error) {
        Log.i("MICHELE", "onError");
        Log.e("MICHELE", error);
        isRecording = false;
        if (!isSopStarted && zephyerScanningTime != 0) {
            isSopStarted = true;
            new Handler(getMainLooper()).postDelayed(this::disconnectZephyr, 1000);
            // todo Utils.showToast(getApplicationContext(), "Zephyr connection error");
        }
    }

    @Override
    public void onDataReceived(GeneralInfoPacket packet) {
        Log.i("MICHELE", "onDataReceived");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public NotificationChannel createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        CharSequence name = getString(R.string.default_notification_channel_id);
        String description = "Description";
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(getString(R.string.default_notification_channel_id), name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        if (notificationManager != null)
            notificationManager.createNotificationChannel(channel);
        return channel;
    }

    @Override
    public boolean stopService(Intent name) {
        Log.d("MICHELE ZEPHYR", "onDestroy");
        Log.i("Zephyr", "onDestroy");
        isStarted = false;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                stopForeground(true);
                stopSelf();
            } else {
                stopSelf();
            }
        } catch (Exception e) {
            Log.e("Error :: ", e.getLocalizedMessage());
        }
        return super.stopService(name);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MICHELE ZEPHYR", "onDestroy");
        Log.i("Zephyr", "onDestroy");
        isStarted = false;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                stopForeground(true);
                stopSelf();
            } else {
                stopSelf();
            }
        } catch (Exception e) {
            Log.e("Error :: ", e.getLocalizedMessage());
        }
    }
}

Поэтому, если я получил конкретное сообщение pu sh, я выполняю этот код, чтобы остановить эту службу.

Чтобы остановить службу, я использовал этот код:

 stopService(new Intent(getApplicationContext(), ZeplyrServiceSweetblue.class));

Но если я попытаюсь выполнить этот код, метод onStop или onDestroy метода ZephyrServiceSweetblue не будет выполнен.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...