1.
Public class globalvariables { publicstatic UserBean User;}
2.
Public classGlobalVariablesImplementsSerializable, cloneable {/*** @Fields: Serialversionuid*/ Private Static Final LongSerialversionuid = 1L; Private StaticGlobalVariables instance; Privateglobalvariables () {} Public Staticglobalvariables getinstance () {if(Instance = =NULL) {Object Object=Utils.restoreobject (Appconstants.cachedir+TAG); if(Object = =NULL) {//The first time the app starts, the file does not exist and the newObject =NewGlobalVariables (); Utils.saveobject (Appconstants.cachedir+TAG, object); } instance=(GlobalVariables) object; } returninstance; } Public Final StaticString TAG = "GlobalVariables"; PrivateUserBean User; PublicUserBean GetUser () {returnuser; } Public voidsetUser (UserBean user) { This. user =user; Utils.saveobject (Appconstants.cachedir+ TAG, This); } //————— The following 3 methods for serializing ———————— Publicglobalvariables readresolve ()throwsObjectstreamexception, clonenotsupportedexception {instance= (globalvariables) This. Clone (); returninstance; } Private voidreadobject (ObjectInputStream ois)throwsIOException, ClassNotFoundException {ois.defaultreadobject (); } PublicObject Clone ()throwsclonenotsupportedexception {return Super. Clone (); } Public voidReset () {User=NULL; Utils.saveobject (Appconstants.cachedir+ TAG, This); }}
3.
Public Static Final voidsaveobject (String path, Object saveobject) {FileOutputStream fos=NULL; ObjectOutputStream Oos=NULL; File F=NewFile (path); Try{fos=NewFileOutputStream (f); Oos=NewObjectOutputStream (FOS); Oos.writeobject (Saveobject); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally { Try { if(Oos! =NULL) {oos.close (); } if(Fos! =NULL) {fos.close (); } } Catch(IOException e) {e.printstacktrace (); } } }
4.
Public Static FinalObject restoreobject (String path) {FileInputStream fis=NULL; ObjectInputStream Ois=NULL; Object Object=NULL; File F=NewFile (path); if(!f.exists ()) { return NULL; } Try{FIS=NewFileInputStream (f); Ois=NewObjectInputStream (FIS); Object=Ois.readobject (); returnobject; } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } Catch(ClassNotFoundException e) {e.printstacktrace (); } finally { Try { if(Ois! =NULL) {ois.close (); } if(FIS! =NULL) {fis.close (); } } Catch(IOException e) {e.printstacktrace (); } } returnobject; }
5.
Private void gotologinactivity () { new UserBean (); User.setusername ("Jianqiang"); User.setcountry ("Beijing"); User.setage (+); New Intent (loginnew2activity. this, personcenteractivity. class ); Globalvariables.getinstance (). SetUser (user); StartActivity (intent); }
6.
protected void Initvariables () { = globalvariables.getinstance (). GetUser (); int age = user.getage (); }
7.
Globalvariables.getinstance (). reset ();
8.
Public void Reset () { null; This ); }
9.
10.
3rd Chapter Code