Solved! I may have confused you with my question. what I did was I created a Started service class. override onStartCommand() in myService class after calling startService(intent) from the MainActivity class and create a new class that extends ContentObserver then overrride onChange() method in my ContentObserver class.
how to create a service to interact with a content provider?
-
01-06-2022 - |
Question
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor mCallCursor = getContentResolver().query(
CallLog.Calls.CONTENT_URI, null, CallLog.Calls.TYPE + "=?",
new String[] { String.valueOf(CallLog.Calls.MISSED_TYPE) },
strOrder);
// get start of cursor
if (mCallCursor.moveToFirst()) {
// loop through cursor
do {
mCall = mCallCursor.getString(mCallCursor
.getColumnIndex(CallLog.Calls.NUMBER));
Toast.makeText(getBaseContext(), mCall + " ",
Toast.LENGTH_SHORT).show();
} while (mCallCursor.moveToNext());
}
My app needs to run in the background using a service, but I don't know how to accomplish that. I created a class to access the call logs content provider, specifically the missed calls, so that when a certain number failed to reach the user for 3 consecutive tries, it will set the ringer on if the phone is silent.
Solution 2
OTHER TIPS
Check the documentation of AlarmManager, BroadcastReceiver and IntentService. You will need all of them because:
- You probably don't want your Service to be running all the time, but periodically (e.g. once every 2 minutes). For this you will need to register a broadcast with the AlarmManager, which your BroadcastReceiver will pick up periodically.
- You will be accessing a ContentProvider, and you always do that on a worker thread (and not the main thread) to avoid "Application Not Responding" errors. Starting an IntentService upon receiving a broadcast would ensure that you perform your queries (and resulting actions) in a worker thread (IntentService.onHandleIntent() is guaranteed to run off-main-thread) and because it is also a true Android Service your app is guaranteed to remain alive while you are processing.
I would go about it something like this:
- Create a BroadcastReceiver that listens for BOOT_COMPLETED and your own defined broadcast ACTION.
- Upon receiving BOOT_COMPLETED, register your broadcast ACTION with the AlarmManager. Let it fire periodically (AlarmManager.setRepeating()).
- Upon receiving the broadcast with your own custom ACTION in your BroadcastReceiver, start your IntentService (Context.startService()).
- In your IntentService, perform the required queries, set volume etc.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow