I am trying to put a Parcelable
object that uses an Executor
internally into a Bundle, but appearently the Bundle class copies the object by means of reflection instaid of using the Parcelable
interface.
However this leaves the Executor
in a corrupt state after restoring the object from the Bundle
. Is there a good way to avoid this and make it so my Executor
gets closed and recreated properly?`
This simpplyfied code illustrates my problem:
Example main activity:
public class MainSimple extends AppCompatActivity {
private static final String KEY = "key";
private MyObject object;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (savedInstanceState != null)
object = savedInstanceState.getParcelable(KEY);
else
object = new MyObject("State");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY, object);
}
}
Object that has the Executor
in it:
public class MyObject implements Parcelable {
private ExecutorService es;
private String state;
public MyObject(String state) {
this.state = state;
es = Executors.newSingleThreadExecutor();
}
protected MyObject(Parcel in) {
//Not called when bundling
state = in.readString();
es = Executors.newSingleThreadExecutor();
}
public void run() {
//do something with es
es.submit(() -> Log.d("DEBUG","HELLO WORLD"));
}
public static final Creator<MyObject> CREATOR = new Creator<MyObject>() {
@Override
public MyObject createFromParcel(Parcel in) {
return new MyObject(in);
}
@Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(state);
}
}
When MyObject
is reloaded from the Bundle
the Executor
doesn't work any more.
Aucun commentaire:
Enregistrer un commentaire