I have been reading the Android documentation and I am wondering if anyone can shed some light on what happens to a service instance when a service started with START_STICKY has
When a process is killed and recreated, it goes through the entire lifecycle again (starting at onCreate). Depending on how it was killed and how you save data it may or may not be available to you.
As for getting the intent back, there's a flag for START_REDELIVER_INTENT that will redeliver the intent.
use Internal Storage for Saving object or its field individually.
public void writeToInternalStorage(String fileName,String userName)
{
try{
String endOfLine = System.getProperty("line.separator");
StringBuffer buffer = new StringBuffer();
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE); //// MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
buffer.append(userName.toString() + endOfLine);
fos.write(buffer.toString().getBytes());
Log.v(TAG, "writeFileToInternalStorage complete.. " + buffer.toString());
// writer.write(userName);
fos.close();
}
catch(Exception e)
{
Log.v(TAG, "Error: " + e.getMessage());
ExceptionNotificationMessage("writeToInternalStorage() Error: " + e.getMessage());
}
}
public String readFromInternalStorage(String fileName)
{
try{
File file = this.getFileStreamPath(fileName);
if(file.exists() == true)
{
Log.v(TAG, "readFileFromInternalStorage File found...");
FileInputStream fis = openFileInput(fileName);
StringBuilder buffer = new StringBuilder();
int ch;
while( (ch = fis.read()) != -1){
buffer.append((char)ch);
}
Log.v(TAG, "readFileFromInternalStorage complete.. " + buffer.toString());
fis.close();
return buffer.toString();
}
}
catch(Exception e)
{
Log.v(TAG, "Error: " + e.getMessage());
ExceptionNotificationMessage("readFromInternalStorage() Error: " + e.getMessage());
}
return "";
}
I recently came across this same problem. Service provides no built in means of saving state and the last intent may not be enough to get the service back to its previous state. My solution was to have the activity persist state and pass that state to the service via startService(). The service then just fires events at the activity, like:
This approach cleaned up my design a lot, and both service and activity are resilient to being killed.
Android will not re-populate 'lost' data values when it re-starts your service so your code needs to cater for this eventuality.
My approach is to use all non-primitive state variables and to leave them as null. That way I can test for null and take appropriate steps to initialise them as and when.
I have taken to storing lightweight data that I want to persist across application restarts in the application's preferences.