This is the sixth in our interview series. In this installment, we’ll look at the two commit methods for SharePrefrence: Apply () and commit().

How to understand the lifecycle of an Activity Android Interview (3) : Is it really a good idea to update the UI with BroadcastReceiver? Do you really feel comfortable answering the phone? Explore the Android Handler

start

Interestingly enough, SharePrefrence is often used in development to store lightweight data, such as whether it is the first startup, the first startup goes to the boot page, otherwise it goes straight to the home page, or some other application scenario.

And we’re all familiar with it.

  • Get the SharedPreferences object based on the Context
  • Get the Editor object using the edit() method.
  • Store key-value key-value pair data through the Editor object.
  • Commit the data with the commit() method.
public class SplashActivity extends AppCompatActivity {
    public static final String SP_KEY = "com.zxedu.myapplication.SplashActivity_SP_KEY";
    public static final String IS_FIRST_IN = "com.zxedu.myapplication.SplashActivity_IS_FIRST_IN";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Some business code. SharedPreferences preferences = getSharedPreferences("name",MODE_PRIVATE);
        if (preferences.getBoolean(IS_FIRST_IN,true)) {// Jump to the boot page
            startActivity(new Intent(this,GuideActivity.class));
            finish();
        }else{
            // Jump to the main page
            startActivity(new Intent(this,MainActivity.class)); }}}public class GuideActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        getSharedPreferences(SplashActivity.SP_KEY,MODE_PRIVATE).edit().putBoolean(SplashActivity.IS_FIRST_IN,false).apply(); }}Copy the code

As you can see from the code, it’s a bit of a mess, nothing special, but early developers should know that we used to prefer commit(). Android Studio now emits a yellow warning when we commit directly using commit().

nanchen

What are the differences between commit() and apply()?

First, the similarities:

  • Both submit Prefrence modification data;
  • Both are atomic processes.

Commit (); commit();

/**
         * Commit your preferences changes back from this Editor to the
         * {@link SharedPreferences} object it is editing.  This atomically
         * performs the requested modifications, replacing whatever is currently
         * in the SharedPreferences.
         *
         * <p>Note that when two editors are modifying preferences at the same
         * time, the last one to call commit wins.
         *
         * <p>If you don't care about the return value and you're
         * using this from your application's main thread, consider
         * using {@link #apply} instead.
         *
         * @return Returns true if the new values were successfully written
         * to persistent storage.
         */
        boolean commit(a);Copy the code

The commit() method has two comments:

  • The execution result is returned.
  • This can be considered if the result is not considered and executed on the main threadapply().

Look again at the definition of the apply() method:

/**
         * Commit your preferences changes back from this Editor to the
         * {@link SharedPreferences} object it is editing.  This atomically
         * performs the requested modifications, replacing whatever is currently
         * in the SharedPreferences.
         *
         * <p>Note that when two editors are modifying preferences at the same
         * time, the last one to call apply wins.
         *
         * <p>Unlike {@link #commit}, which writes its preferences out
         * to persistent storage synchronously, {@link #apply}
         * commits its changes to the in-memory
         * {@link SharedPreferences} immediately but starts an
         * asynchronous commit to disk and you won't be notified of
         * any failures.  If another editor on this
         * {@link SharedPreferences} does a regular {@link #commit}
         * while a {@link #apply} is still outstanding, the
         * {@link #commit} will block until all async commits are
         * completed as well as the commit itself.
         *
         * <p>As {@link SharedPreferences} instances are singletons within
         * a process, it's safe to replace any instance of {@link #commit} with
         * {@link #apply} if you were already ignoring the return value.
         *
         * <p>You don't need to worry about Android component
         * lifecycles and their interaction with <code>apply()</code>
         * writing to disk.  The framework makes sure in-flight disk
         * writes from <code>apply()</code> complete before switching
         * states.
         *
         * <p class='note'>The SharedPreferences.Editor interface
         * isn't expected to be implemented directly.  However, if you
         * previously did implement it and are now getting errors
         * about missing <code>apply()</code>, you can simply call
         * {@link #commit} from <code>apply()</code>.
         */
        void apply(a);Copy the code

The difference between Apply () and commit() is that it uses asynchrony instead of synchronization, commits changes immediately to memory and then asynchronously to hard disk, and there is no warning if it fails.

To summarize the differences:

  • commit()Is directly and synchronously committed to the hardware disk, therefore, multiple concurrent usescommit()When you make a commit, they wait for what’s being processedcommit()Saving the data to the disk reduces efficiency. whileapply()It’s just atomic submission to content, called laterapply()Function to operate asynchronously.
  • Turn the source can be foundapply()The return value is void andcommit()Returns a Boolean value indicating whether the submission was successful.
  • apply()Methods do not have any hint of failure.

Commit () or apply()?

In most cases, we are in the same process and SharedPrefrence is a single instance, so there is no concurrency conflict. If you don’t care about the result of the submission, we highly recommend using apply(). You still need commit().


nanchen