D
D
Dutymy2021-08-13 03:42:24
Java
Dutymy, 2021-08-13 03:42:24

How to create a static class?

Hello, I need to group functions, for example into a class.

static public class overlayService {
        static private Intent overlayServiceIntent = new Intent(getApplicationContext(), OverlayService.class);
        static public boolean overlayBound;

        static public void start() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(overlayServiceIntent);
            } else {
                startService(overlayServiceIntent);
            }
        }

        static public void bind() {
            bindService(overlayServiceIntent, overlayConnection, Context.BIND_AUTO_CREATE);
        }

        static public void unbind() {
            unbindService(overlayConnection);
        }

        static public void stop() {
            stopService(overlayServiceIntent);
        }
    }

Outside the class is
ServiceConnection overlayConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            overlayService.overlayBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            overlayService.overlayBound = false;
        }
    };

But the compiler swears that I did wrong))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-08-13
@Dutymy

A static class only makes sense when it is nested within another class. In this case, it will not have access to the non-static fields of the enclosing class.
Therefore, static is simply superfluous here.
On the other hand, it is not clear what you want to do. It looks like you have some kind of this on which you call the getApplicationContext, bindService and so on methods. Is this an activity? In any case, this is some kind of context, and the combination of the words "static" and "Context" immediately alarms me. Most likely, you are doing something wrong, and all these methods of yours should be just private methods of your activity in the simplest case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question