In one of my Apps I do have a FileCache in a library project. The App itself has a Service waiting for notfications when the FileCache in the library has cached a new file.
The library is an Android library project and included in the App.
What’s the best way to send a notification from the library to the App Service?
-
Sending a Broadcast needs to know the Receiver in the Service. This is not possible from within the library project.
-
Calling a function within the Service from the library code isn’t possible neither.
Here’s a code skeleton:
// This is in the App
public class MyService extends Service implements OnBufferingUpdateListener, OnCompletionListener, OnErrorListener, OnInfoListener, OnPreparedListener {
public class MyBroadcastReceiver extends BroadcastReceiver {
public static final String BROADCASTRECEIVER = "xx.yyy.zzzzz.MyService.MyBroadcastReceiver";
@Override
public void onReceive(final Context context, final Intent intent) {
}
}
}
// This is in a library project that's included in the App
public class FileCache {
private void doThread() {
final Handler handler = new Handler() {
@Override
public void handleMessage(final Message message) {
try {
if (processed.size() > 0) {
//TODO: Notification to Service
processed.clear();
}
} catch (NullPointerException nullPointerException) {
//TODO:
}
if (queue.size() > 0) {
doThread();
} else {
running = false;
}
}
};
new Thread() {
@Override
public void run() {
for (Map.Entry<String, QueueElement> entry : queue.entrySet()) {
QueueElement element = entry.getValue();
if (element != null) {
File file = fetch(element.url);
if (file != null) {
ProcessedElement processedElement = new ProcessedElement();
processedElement.file = file;
processedElement.url = element.url;
processed.put(entry.getKey(), processedElement);
}
}
deleteFromQueue(entry.getKey());
}
handler.sendEmptyMessage(0);
}
}.start();
}
}
Sure it is. Have the client of your library project supply to the library enough information, via parameters on some method, to either:
Identify the service (e.g., service
Classobject), in which case you usestartService()to send a command to the service, orIdentify the
BroadcastReceiver(e.g., the action string used by itsIntentFilter), in which case you usesendBroadcast()