I would like to find out if the following is possible. I want to have an activity and a service that both make changes to a database, will the service still be able to access and change the content of the database once the activity stops running?
I know that the service can run independent of the activity once it is closed, but just not sure if database access will still be able to continue?
Server-side database Systems designers report success using SQLite as a data store on server applications running in the datacenter, or in other words, using SQLite as the underlying storage engine for an application-specific database server.
We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.
If you need to manage data in a private database, use the android. database. sqlite classes. These classes are used to manage the Cursor object returned from a content provider query.
Yes, you can use sqlite database in your Service, even if application goes to background, or application is killed using swipe from Recent application list.
I created a very simple demo.
Its just a database with an empty table. And I am getting whether table contains any record or not in Service at every 10 seconds. Its giving me toast message even if application is in background, or its killed.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Handler mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
MyDBHelper myDBHelper = new MyDBHelper(getApplicationContext());
boolean isInfoAvailable = myDBHelper.isAnyInfoAvailable(getApplicationContext());
Toast.makeText(getApplicationContext(), String.valueOf(isInfoAvailable), Toast.LENGTH_LONG).show();
mHandler.postDelayed(mRunnable, 10 * 1000);
}
};
mHandler.postDelayed(mRunnable, 10 * 1000);
return super.onStartCommand(intent, flags, startId);
}
All you would need to make sure is:
Service should run in background.
In your manifest file, use flag android:stopWithTask="false"
for service.
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false">
</service>
Hope this helps. :)
It is entirely possible to have your service access the DB - try looking at How to use SQLite from Services in Android?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With