Can I access the database from a service?

I want to access a database from my service, which runs in the background. Is it possible?

+4
source share
4 answers

Yes, you can access your database from the service. To access the database, all you need is a Context , which is also available in the service.

+3
source

Yes, it is possible, and all that is needed is the need to use the contextual use service.

0
source

Yes, this is the usual functionality that we use in the application. @Ajay is right.

EXAMPLE OF USE

You can call the database access method from your service class in a thread that runs in a few seconds.

0
source

Yes, you can access the database from the service. All you have to do is create a database class object that extends SqliteOpenHelper, passes ServiceName.this as a context, or uses your application class as a context.

 DbHelper db = new DbHelper(ServiceClass.this); db.performOperations(); db.close(); 

OR

 DbHelper db = new DbHelper(YourApplicationClass.getAppContext()); db.performOperations(); db.close(); 
0
source

Source: https://habr.com/ru/post/1396568/


All Articles