Android self-study note-13-ContentObserver content observer

Source: Internet
Author: User

I haven't updated my blog for a long time. Recently I am busy with training at the company. On the one hand, I am a little busy, on the other hand I am lazy, so I have never updated my blog. Now let's get down to the point. Today we will briefly introduce ContentObserver in Android.

The translation of ContentObserver into Chinese is the content observer, which aims to observe (capture) The database changes caused by a specific Uri, and then perform some corresponding processing. ContentObserver is generally used together with the Provider provided by the system or a third-party program. These providers generally have a Uri, and then ContentObserver listens to changes in the Uri data and then processes the changes accordingly.

The steps for using ContentObserver are summarized as follows:

1. First create a ContentObserver subclass, and then implement the onChange method. When the data in the listener Uri changes, the onchange method is called.

2. register the ContentObserver.

The following code is a simple example:

Subclass of ContentObserver

Package com. qin. contentobserver; import android. content. context; import android. database. contentObserver; import android.net. uri; import android. OS. handler; import android. provider. *; import android. provider. settings. settingNotFoundException; import android. util. log; // used to check whether the row of the flight mode in the system table has changed. The "row" content observer public class AirplaneContentObserver extends ContentObserver {private static String TAG = "AirplaneContentObserver "; private static int MSG_AIRPLANE = 1; private Context mContext; private Handler mHandler; // This Handler is used to update the UI thread public AirplaneContentObserver (Context context, Handler handler) {super (handler ); mContext = context; mHandler = handler;}/*** when the monitored Uri changes, this method will be called back ** @ param selfChange this value is of little significance in general, this callback value is false */@ Overridepublic void onChange (boolean selfChange) {Log. I (TAG, "------------- the airplane mode has changed -------------"); // whether the system is in flight mode try {int isAirplaneOpen = Settings. system. getInt (mContext. getContentResolver (), Settings. global. AIRPLANE_MODE_ON); Log. I (TAG, "isAirplaneOpen ----->" + isAirplaneOpen); mHandler. obtainMessage (MSG_AIRPLANE, isAirplaneOpen ). sendToTarget ();} catch (SettingNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}

Here we can see that we have defined a constructor with parameters. The second parameter is Handler, because our custom AirplaneContentObserver is a non-main thread when running the program, in Android, non-main threads cannot modify the UI. Therefore, if we want to modify the UI, we need to send a message to Handler first. Then, after the Handler in the main thread receives the sent message, it will call the handleMessage method, then perform some processing or updating the UI. Therefore, the Handler parameter here needs to be created in the main thread and then passed to the class object when it is called.

The MainActivity. java class is given below:

Package com. qin. contentobserver; import android. app. activity; import android. database. cursor; import android.net. uri; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. provider. *; import android. util. log; import android. widget. editText; import android. widget. textView; public class MainActivity extends Activity {private TextView tvAirplane; private EditText etSmsoutb Ox; // Message Type value: private static final int MSG_AIRPLANE = 1; private static final int MSG_OUTBOXCONTENT = 2; private AirplaneContentObserver airplaneCO;/** Called when the activity is first created. * // @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); tvAirplane = (TextView) findViewById (R. id. tvAirplane); etSmsoutbox = (EditText) FindViewById (R. id. smsoutboxContent); // create two objects airplaneCO = new AirplaneContentObserver (this, mHandler); // register the content observer registerContentObservers ();} private void registerContentObservers () {// call the getUriFor method to obtain the UriUri airplaneUri = Settings for the row of the "flight mode" in the system table. system. getUriFor (Settings. global. AIRPLANE_MODE_ON); // register the content observer // The second parameter false is exact match getContentResolver (). registerContentObserver (airplaneUri, false, air PlaneCO);} private Handler mHandler = new Handler () {public void handleMessage (Message msg) {System. out. println ("--- mHanlder ----"); switch (msg. what) {case MSG_AIRPLANE: int isAirplaneOpen = (Integer) msg. obj; if (isAirplaneOpen! = 0) tvAirplane. setText ("flight mode enabled"); else if (isAirplaneOpen = 0) tvAirplane. setText ("flight mode disabled"); break; default: break ;}}};}
In the code above, we registered a content observer who monitors the changes in the mobile phone flight mode. When we modify our flight mode, the results displayed on the page will also change accordingly.

Example of Engineering: http://download.csdn.net/detail/mengxiangyue/7169579

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.