Android contentobserver Monitor Gallery changes

Source: Internet
Author: User

Compared to fileobserver cumbersome, contentobserver in the ease of use is still to be excellent, so we can listen to the need to choose, a function of a more than one way of realization, more than a comparison.

About Contentobserver

Contentobserver as the name implies, is the meaning of the content observer, and fileobserver very similar, but the former is a monitoring database changes.

Implementation steps

Here we take an example of a gallery monitor:
Give the URI of the database relative to the gallery before doing it:

MediaStore.Images.Media.EXTERNAL_CONTENT_URI

This URI is critical, it points to the database we need to listen to the image library, there are many URIs, interested can go to check, here do not extend.

1. Implement your own Content viewer

Like Fileobserver, Contentobserver is also an abstract class that requires us to inherit the implementation so the first step is to implement your own content viewer:

public class Screenshotcontentobserver extends Contentobserver {private Context mcontext;    Private Handler Mhandler;        Public Screenshotcontentobsetver (context context, Handler Handler) {super (Handler);          Mcontext = context;  Mhandler = handler; It is best to pass the handler of the main thread so that it facilitates communication and update the UI}/** * responds to database changes primarily in OnChange, and handles them accordingly. */@Override public void OnChange (b        Oolean selfchange) {super.onchange (selfchange); /*---------------Handle----------------*/LOG.I (Mainactivity.tag, "database is changed!---------------------------        ---------------");        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;        cursor cursor = mcontext.getcontentresolver (). Query (URI, NULL, NULL, NULL, "_data desc");        if (cursor! = NULL) {LOG.I (Mainactivity.tag, "the number of the data is:" + cursor.getcount ());        StringBuffer sb = new StringBuffer (); while (Cursor.movetonext ()) {String fileName = cursor.getstring (cUrsor.getcolumnindex ("_data"));            String[] A = Filename.split ("/");  LOG.I (Mainactivity.tag, a[a.length-2] + a[a.length-1]);        Observe the output directory name/file name Sb.append ("Directory Name:" + a[a.length-2]);        } cursor.close ();    /* The message is passed to the main thread, and directory information is bound in the message */Mhandler.obtainmessage (0x110, sb.tostring ()). Sendtotarget (); }}
2. Calling in activity
private ScreenshotContentObserver mScreenObserver;private Handler mHandler = new Handler() {    @Override    public void handleMessage(Message msg) {        if (msg.what == 0x110) {            Log.i(TAG, "message is back! " + msg.obj.toString());        }    }};private void listenDB() {    mScreenObserver = new ScreenshotContentObserver(MainActivity.this, mHandler);    registerContentObserver();}private void registerContentObserver() {    /*之前说过,非常关键的Uri*/    Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;    getContentResolver().registerContentObserver(imageUri, false, mScreenObserver);    Log.i(TAG, "registered!---------------------------");}

You only need to call listendb in the activity again.

3. Rights statement

Finally, add the following permissions to the manifest file

<!--往sdcard中写入数据的权限 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission><!--在sdcard中创建/删除文件的权限 --><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>

Note that depending on the URI you are listening to may require special permissions, such as listening to contacts, you need to check the permissions of the contact, this need to pay attention to.

Summarize

Relative to the fileobserver of the various dark pits, contentobserver is still very useful, the response speed should be the former faster, because after all, is directly listening to the file directory. There's time for this later. I can look at the efficiency comparison between the two.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android contentobserver Monitor Gallery changes

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.