I couldn\'t find any examples of how to send messages between an activity and a service, and I have spent far too many hours figuring this out. Here is an example project fo
For sending data to a service you can use:
Intent intent = new Intent(getApplicationContext(), YourService.class);
intent.putExtra("SomeData","ItValue");
startService(intent);
And after in service in onStartCommand() get data from intent.
For sending data or event from a service to an application (for one or more activities):
private void sendBroadcastMessage(String intentFilterName, int arg1, String extraKey) {
Intent intent = new Intent(intentFilterName);
if (arg1 != -1 && extraKey != null) {
intent.putExtra(extraKey, arg1);
}
sendBroadcast(intent);
}
This method is calling from your service. You can simply send data for your Activity.
private void someTaskInYourService(){
//For example you downloading from server 1000 files
for(int i = 0; i < 1000; i++) {
Thread.sleep(5000) // 5 seconds. Catch in try-catch block
sendBroadCastMessage(Events.UPDATE_DOWNLOADING_PROGRESSBAR, i,0,"up_download_progress");
}
For receiving an event with data, create and register method registerBroadcastReceivers() in your activity:
private void registerBroadcastReceivers(){
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int arg1 = intent.getIntExtra("up_download_progress",0);
progressBar.setProgress(arg1);
}
};
IntentFilter progressfilter = new IntentFilter(Events.UPDATE_DOWNLOADING_PROGRESS);
registerReceiver(broadcastReceiver,progressfilter);
For sending more data, you can modify method sendBroadcastMessage();
. Remember: you must register broadcasts in onResume() & unregister in onStop() methods!
UPDATE
Please don't use my type of communication between Activity & Service. This is the wrong way. For a better experience please use special libs, such us:
1) EventBus from greenrobot
2) Otto from Square Inc
P.S. I'm only using EventBus from greenrobot in my projects,
Note: You don't need to check if your service is running, CheckIfServiceIsRunning()
, because bindService()
will start it if it isn't running.
Also: if you rotate the phone you don't want it to bindService()
again, because onCreate()
will be called again. Be sure to define onConfigurationChanged()
to prevent this.
Message msg = Message.obtain(null, 2, 0, 0);
Bundle bundle = new Bundle();
bundle.putString("url", url);
bundle.putString("names", names);
bundle.putString("captions",captions);
msg.setData(bundle);
So you send it to the service. Afterward receive.