0

I have my main activity and I have a service (which runs even in the background when the app is closed). I would like to be writing to the same file from the activity AND from the service. what would be the right way to achieve this (design wise)?

One solution is to have a global variable to tell me if the service is currently writing or if the Activity is doing it ( so I dont end up openning the file twice). Another way is bind the service to the activity and the activity can only write to file by calling a method on the service

Any idea is appreciated

Thanks

Snake
  • 14,228
  • 27
  • 117
  • 250

2 Answers2

0

It is better way to write file in service, Your flow will be like below If I have understand your problem I guess Start application Activity -> Provide info regarding writing file to service -> Start service -> Write file -> Send brodcast to your application

Write a broadcast receiver -> It receive your broadcast when writing file is completed.

Anand Phadke
  • 531
  • 3
  • 28
  • The problem is that my service is not created for the only purpose of writing to a file. The service is running already, and it will have to write its status to the file regularly. IN ADDITION, Activity has to write to the same file its status on regular interval – Snake Jan 17 '15 at 07:50
0

It would be better if you don't write the file directly from your Activity because this might cause concurrency conflicts with your Service. It would be better if you request your Service from the Activity to write some thing to that file.

Activity<------>Service<------->File

Make a method inside the Service and call it in your Activity with required/desired parameters by this you can avoid the conflicts as only the Service will be writing to the File.

SMR
  • 6,628
  • 2
  • 35
  • 56
  • Thank you How can I call a method on the service? I guess I need to bind the service to the activity so I can call its method right? StartService does not give me a reference to the service ( I assume) – Snake Jan 17 '15 at 07:46