Save the status by using annotations in the Activity.

Source: Internet
Author: User

Save the status by using annotations in the Activity.
For more information, see http://blog.csdn.net/allen315#/article/details/43567229.

Generally, when the onPause () and onStop () Methods of Activity are called during development, the Activity instance is not directly destroyed and is still stored in the memory, all information and status data in the Activity will be saved. When the Activity returns to the foreground, all data will be retained and available.

However, in some special circumstances, for example, when a device is loaded with tools such as "XX master" and "XX assistant" to clean up memory, it is also possible to directly kill our background Activity, in another case, when the system memory is insufficient, the garbage collection mechanism is automatically recycled to the Activity we have previously onPause () and onStop (). In this case, the information and status data in the Activity disappear. When the Activity is restarted, no data is found. In this case, our programmers can save the data that needs to be preserved locally before the Activity is destroyed. SharedPrefence is a good choice, but it seems a little more troublesome to do so.


General Solution

Another method is to use the onSaveInstanceState (Bundle outState) method in the Activity to save data. The onSaveInstanceState (Bundle outState) method transmits a Bundle object, we use the Bundle object to put some data to be saved. When we re-place the Activity to the foreground, we first judge whether the Bundle is empty in the onCreate () method, you can choose to use the data based on the judgment conditions, or directly rewrite the onRestoreInstanceState (Bundle savedInstanceState) method in the Activity to retrieve the data. For example:

Public class ExampleActivity1 extends Activity {private String mState; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); if (savedInstanceState! = Null) {mState = savedInstanceState. getString ("state") ;}// this method is called before the Activity is recycled to save the data @ Overrideprotected void onSaveInstanceState (Bundle outState) {super. onSaveInstanceState (outState); outState. putString ("state", mState) ;}// you can also restore data in this method @ Overrideprotected void onRestoreInstanceState (Bundle savedInstanceState) {super. onRestoreInstanceState (savedInstanceState); mState = savedInstanceState. getString ("state ");}}

The above lines of simple code can solve the Activity state saving problem, but there is a problem. What if we need to save more than one or two data types? Alternatively, we can constantly putXXX () different data into the Bundle, and then use different data in getXXX. There is no problem with the feasibility, but it seems a little complicated. The following describes how to use annotations to simplify unnecessary repetitive operations and greatly simplify the writing of source code.


Save status information using annotations

The following is the complete implementation code, which is difficult to understand. To facilitate use in the Activity, you need to create a base class BaseActivity of the Activity and write the code in the base class, if no new Activity instance is created in the future, BaseActivity must be inherited to ensure that each Activity has a corresponding state information storage method.

Package com. example. activitystatesave; import java. io. serializable; import java. lang. annotation. annotation; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; import java. lang. reflect. field; import android. app. activity; import android. OS. bundle; import android. OS. parcelable; import android. util. log; pu Blic class BaseActivity extends Activity {private final String TAG = "BaseActivity"; @ Retention (RetentionPolicy. RUNTIME) @ Target (ElementType. FIELD) public @ interface SavedInstanceState {}@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // restore data if (savedInstanceState! = Null) {restoreInstanceState (savedInstanceState) ;}/ *** save status */@ Overrideprotected void onSaveInstanceState (Bundle outState) {Field [] fields = this. getClass (). getDeclaredFields (); Field. setAccessible (fields, true); Annotation [] ans; for (Field f: fields) {ans = f. getDeclaredAnnotations (); for (Annotation an: ans) {if (an instanceof SavedInstanceState) {try {Object o = f. get (this); if (o = null) {continue;} String fieldName = f. getName (); if (o instanceof Integer) {outState. putInt (fieldName, f. getInt (this);} else if (o instanceof String) {outState. putString (fieldName, (String) f. get (this);} else if (o instanceof Long) {outState. putLong (fieldName, f. getLong (this);} else if (o instanceof Short) {outState. putShort (fieldName, f. getShort (this);} else if (o instanceof Boolean) {outState. putBoolean (fieldName, f. getBoolean (this);} else if (o instanceof Byte) {outState. putByte (fieldName, f. getByte (this);} else if (o instanceof Character) {outState. putChar (fieldName, f. getChar (this);} else if (o instanceof CharSequence) {outState. putCharSequence (fieldName, (CharSequence) f. get (this);} else if (o instanceof Float) {outState. putFloat (fieldName, f. getFloat (this);} else if (o instanceof Double) {outState. putDouble (fieldName, f. getDouble (this);} else if (o instanceof String []) {outState. putStringArray (fieldName, (String []) f. get (this);} else if (o instanceof Parcelable) {outState. putParcelable (fieldName, (Parcelable) f. get (this);} else if (o instanceof Serializable) {outState. putSerializable (fieldName, (Serializable) f. get (this);} else if (o instanceof Bundle) {outState. putBundle (fieldName, (Bundle) f. get (this) ;}} catch (IllegalArgumentException e) {Log. e (TAG, e. getMessage ();} catch (IllegalAccessException e) {Log. e (TAG, e. getMessage ();} catch (Exception e) {Log. e (TAG, e. getMessage () ;}}} super. onSaveInstanceState (outState);}/*** recover data here ** @ param savedInstanceState */private void restoreInstanceState (Bundle savedInstanceState) {Field [] fields = this. getClass (). getDeclaredFields (); Field. setAccessible (fields, true); Annotation [] ans; for (Field f: fields) {ans = f. getDeclaredAnnotations (); for (Annotation an: ans) {if (an instanceof SavedInstanceState) {try {String fieldName = f. getName (); Class cls = f. getType (); if (cls = int. class | cls = Integer. class) {f. setInt (this, savedInstanceState. getInt (fieldName);} else if (String. class. isAssignableFrom (cls) {f. set (this, savedInstanceState. getString (fieldName);} else if (Serializable. class. isAssignableFrom (cls) {f. set (this, savedInstanceState. getSerializable (fieldName);} else if (cls = long. class | cls = Long. class) {f. setLong (this, savedInstanceState. getLong (fieldName);} else if (cls = short. class | cls = Short. class) {f. setShort (this, savedInstanceState. getShort (fieldName);} else if (cls = boolean. class | cls = Boolean. class) {f. setBoolean (this, savedInstanceState. getBoolean (fieldName);} else if (cls = byte. class | cls = Byte. class) {f. setByte (this, savedInstanceState. getByte (fieldName);} else if (cls = char. class | cls = Character. class) {f. setChar (this, savedInstanceState. getChar (fieldName);} else if (CharSequence. class. isAssignableFrom (cls) {f. set (this, savedInstanceState. getCharSequence (fieldName);} else if (cls = float. class | cls = Float. class) {f. setFloat (this, savedInstanceState. getFloat (fieldName);} else if (cls = double. class | cls = Double. class) {f. setDouble (this, savedInstanceState. getDouble (fieldName);} else if (String []. class. isAssignableFrom (cls) {f. set (this, savedInstanceState. getStringArray (fieldName);} else if (Parcelable. class. isAssignableFrom (cls) {f. set (this, savedInstanceState. getParcelable (fieldName);} else if (Bundle. class. isAssignableFrom (cls) {f. set (this, savedInstanceState. getBundle (fieldName);} catch (IllegalArgumentException e) {Log. e (TAG, e. getMessage ();} catch (IllegalAccessException e) {Log. e (TAG, e. getMessage ();} catch (Exception e) {Log. e (TAG, e. getMessage ());}}}}}}

The above is the source code of all baseactivities. When used, the new Activity extends BaseActivity is created, and the data of the member variable Filed needs to be saved. This defined annotation is added to the member variable Filed. For more information about annotations, see annotations!



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.