janishar/android-mvvm-architecture

How we can use Service class?

RupeshVM opened this issue · 6 comments

I want to insert data inside local db from service class.

I will add the example soon.

Im facing with your issues.
Have any body can solve this problem?

We have the service class example in this project.

Follow below steps to inject Data Manager instance in service class

  1. Create ServiceBuilderModule class
@Module
public abstract class ServiceBuilderModule {

   // Note: Add all your application service classes here
   // As an example I am adding IdentifyAppClearedFromRecentService
    @ContributesAndroidInjector
    abstract IdentifyAppClearedFromRecentsService bindNetworkJob();
}
  1. Add ServiceBuilderModule class in your application component.
    In my application: I haveAppComponent class as below
@Singleton
@Component(modules = {
        AndroidInjectionModule.class,
        ActivityBuilderModule.class,
        ServiceBuilderModule.class})
public interface AppComponent {

    @Component.Builder
    interface Builder {

        @BindsInstance
        Builder application(Application application);

        AppComponent build();
    }

    void inject(SampleApp sampleApp);

    DataManager getDataManager();
}
  1. Finally Inject DataManager instance in IdentifyAppClearedFromRecentsService class as below
public class IdentifyAppClearedFromRecentService extends Service {

    @Inject
    NLearnDataManager dataManager;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        //Code here
        dataManager.stopSync();
        stopSelf();
    }
}

Note: Don't forget to add SampleApp class implement HasServiceInjector as below

public class SampleApp extends Application implements HasActivityInjector,
        HasServiceInjector{

    @Inject
    DispatchingAndroidInjector<Activity> activityDispatchingAndroidInjector;

    @Inject
    DispatchingAndroidInjector<Service> serviceDispatchingAndroidInjector;

    private AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        initializeDaggerComponent();
    }

    private void initializeDaggerComponent() {

        appComponent = DaggerAppComponent.builder().application(this).build();
        appComponent.inject(this);
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityDispatchingAndroidInjector;
    }

    @Override
    public AndroidInjector<Service> serviceInjector() {
        return serviceDispatchingAndroidInjector;
    }
}

@rupvm might this solves your problem.

db insert or send data from db to server example?