Such a question, in the project I use the method to test the service, I rendered it into a separate class with the annotation @Module:
@Module public class IsMyServiceRunning { Context context; public IsMyServiceRunning(Class<?> serviceClass,Context context) { isMyServiceRunnin(serviceClass); this.context = context; } public boolean isMyServiceRunnin(Class<?> serviceClass) { ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager .getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } } In the main activation I write:
public class MainActivity extends Activity implements SurfaceHolder.Callback { @Inject IsMyServiceRunning isMyServiceRunning; Created a class
@Module public class AndroidModule { Context context; public AndroidModule(Context context) { this.context = context; } @SuppressLint("ServiceCast") @Provides @Singleton NotificationManagerCompat manager (Context context) { return (NotificationManagerCompat) context.getSystemService(Context.NOTIFICATION_SERVICE); } @Singleton IsMyServiceRunning isMyServiceRunning(Context context){ return ;//не знаю как правильно возвращать,а главное что именно } } I cannot check the performance at this stage because many parts are not implemented, so I’m clarifying whether I use Dependency Injection correctly in this example? Have I implemented everything?
UPDATE:
@Module public class IsMyServiceRunning { Context context; public IsMyServiceRunning(Context context) { this.context = context; } public boolean isMyServiceRunnin(Class<?> serviceClass) { ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager .getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } } Module:
@Module public class AndroidModule { Context context; public AndroidModule(Context context) { this.context = context; } @SuppressLint("ServiceCast") @Provides @Singleton NotificationManagerCompat manager (Context context) { return (NotificationManagerCompat) context.getSystemService(Context.NOTIFICATION_SERVICE); } @Singleton IsMyServiceRunning isMyServiceRunning(Class<?> serviceClass){ return isMyServiceRunning(serviceClass); } } Mainactivity:
@Inject IsMyServiceRunning isMyServiceRunning;
IsMyServiceRunningobject. Either the constructor of theIsMyServiceRunningclassIsMyServiceRunningbe annotated with Inject, but then you need a module that can provide context. - temq