Reputation: 497
I have data successfully coming from a sensor which I have sent to a service through a broadcast receiver. I now want to pass it to a thread to append it to a file.
I'm following the outline given in this answer.
And have found out how to append to a file here.
What I can't work out is how to keep the file open in the thread, I don't want to have to close it and reopen it every time a message comes in to the thread's message loop. My code broadly follows something I found here (about 1/3rd way down the webpage)
Specific questions as follows:
saveDataToFile(String data)
as being written outside the thread class, but called by the message handler looper, does this mean it is run inside the thread, even though the method is written outside the thread?Code here (note I haven't copied in all the service binding related code:
public class SaveDataService extends Service {
private boolean isBound;
private final IBinder myBinder = new SaveDataServiceBinder();
private SaveDataThread mySaveDataThread;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("save_data")) {
String data = intent.getStringExtra("data");
if (mySaveDataThread.myHandler != null) {
Message msg = mySaveDataThread.myHandler.obtainMessage(0);
msg.obj = data;
mySaveDataThread.myHandler.sendMessage(msg);
}
}
}
};
private class SaveDataThread extends Thread {
public Handler myHandler;
@Override
public void run() {
Looper.prepare();
myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
String data = (String) msg.obj;
saveDataToFile(data);
}
}
};
Looper.loop();
}
}
private void saveDataToFile(String data) {
//save data
}
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("save_data");
registerReceiver(receiver, filter);
mySaveDataThread = new SaveDataThread();
mySaveDataThread.start();
}
@Override
public void onDestroy() {
unregisterReceiver(receiver);
mySaveDataThread.myHandler.getLooper().quit();
}
}
Upvotes: 0
Views: 197
Reputation: 93559
Just keep the open file output stream in a member variable of the Service or Thread.
Upvotes: 1