android: how to restore an object, onResume, and save it onPause?
I want to save a object(Myclass) on pause, and load it when the application resumes.
I tried everything but nothing works.
I'm trying 开发者_开发问答to make a thread and make it run on my main activity when the problem comes. When I press the back button(exit the application) and click again on the application, that creates a new thread and does not resume the old thread.
Make the class (MyClass) implement Serializable
, you can then save it as a file when the activity is destroyed, and restore it from file when it's resumed
public boolean ObjectToFile(String fileName, Object obj){
boolean success = false;
FileOutputStream fos = null;
ObjectOutputStream out = null;
try{
File dir = GetAppDir();
if(dir != null){
fos = new FileOutputStream(dir + "/" + fileName);
out = new ObjectOutputStream(fos);
out.writeObject(obj);
out.close();
success = true;
}
}catch(Exception e){}
return success;
}
public Object FileToObject(String fileName){
Object obj = null;
try{
File dir = GetAppDir();
if(dir != null){
File f = new File(dir, fileName);
if(f.exists() && f.isFile()){
FileInputStream fis = null;
ObjectInputStream in = null;
fis = new FileInputStream(f);
in = new ObjectInputStream(fis);
obj = in.readObject();
in.close();
}
}
}catch(Exception e){}
return obj;
}
Essentially you can't (and shouldn't) do what you're trying to do. If you have code that you want to continue to execute after the user ends a session*, your code should be running in association with a Service. The code should then be writing its work to persistent storage or your Service should allow for some binding interface for the newly created Activity to connect with the Thread.
*A session ends if a user backs our of your Activities. This is a different behavior than the user pressing the HOME key, which indicates that the user wants to resume what they were doing when they return to your application.
精彩评论