0

Ситуация такая. У меня есть приложение которое запускает при нажатии на CheckBox сервис, который работает, даже когда приложение прекращает работу, код внизу. Когда я снова захожу в приложение при нажатии на CheckBox в настройке я хочу отключать этот сервис если в CheckBox не стоит галочки и включать если CheckBox checked. Как мне отключить сервис. Пробовал синглтон, но даже если я не выходил из приложения приложение крашится. Запуск сервиса:

 private boolean isMyServiceRunning(Class<?> serviceClass) {
            ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (serviceClass.getName().equals(service.service.getClassName())) {
                    Log.i ("Service status", "Running");
                    return true;
                }
            }
            Log.i ("Service status", "Not running");
            return false;
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            //пока так потом добавиться может переделаю
            //SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
            boolean isCheck = sharedPreferences.getBoolean(key, false);
            L.i("key=" + key+"isCheck="+isCheck);
            if(isCheck) {
                mServiceIntent = new Intent(getActivity(), MuteService.getInstance().getClass());
                if (!isMyServiceRunning(MuteService.getInstance().getClass())) {
                    getActivity().startService(mServiceIntent);
                }
            } else {
                MuteService.getInstance().stopForeground(false);
            }
        } 

А вот сам сервис:

public class MuteService extends Service implements Observer {

    private static MuteService instanse;

    MuteReceiver mr;

    public MuteService() {
    }

    public static MuteService getInstance() {
        if(instanse== null) {
            instanse = new MuteService();
        }
        return instanse;
    }



    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(1, new Notification());
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        mr = new MuteReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.media.action.MICROPHONE_MUTE_CHANGED");
        this.registerReceiver(mr, filter);
        MuteObservable.getInstance().addObserver(this);
        return Service.START_NOT_STICKY;
    }

    @Override
    public void update(Observable o, Object arg) {


    }

    @Override
    public void onDestroy() {
        unregisterReceiver(mr);
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
        Toast.makeText(getApplicationContext(), "Finish Work service", Toast.LENGTH_LONG).show();
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startMyOwnForeground()
    {
        String NOTIFICATION_CHANNEL_ID = "example.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }


    private void sendNotification(boolean isOff) {
        
    }
}

Вот Restarter

public class Restarter extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Broadcast Listened", "Service tried to stop");
        //Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, MuteService.class));
        } else {
            context.startService(new Intent(context, MuteService.class));
        }
    }
}

1 ответ 1

1

Обычно подразумевается, что если есть метод startЧегоТо(), то должен быть и stopТогоЖе().

If a component starts the service by calling startService() (which results in a call to onStartCommand()), the service continues to run until it stops itself with stopSelf() or another component stops it by calling stopService().

Источник: https://developer.android.com/guide/components/services

stopForeground() же делает из foreground service "обычный", но не останавливает его.

Источник: https://developer.android.com/guide/components/foreground-services#remove-from-foreground

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.