Question

I have a process that pulls Contact info, and it takes a long time - 4 seconds. I do not want it to interfere with the user experience in my app. I have 2 questions:

  1. How can I run this in its own thread so it does not delay the activity from drawing on the screen
  2. Is there a way to speed this up? (Am I doing it inefficiently?)

I've tried calling the getContacts() method below from onCreate, from onStart, and onResume, but in all cases the screen does not appear until after method has run completely.

Here's the code:

private void getContacts() {
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                Log.d("ManageFriends","getContacts Start");
                ContentResolver cr = getContentResolver();
                String[] PROJECTION = new String[] {
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID,
                        ContactsContract.Contacts.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Email.ADDRESS,
                        ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
                };
                String filter = ContactsContract.CommonDataKinds.Email.ADDRESS + " NOT LIKE '' AND 1 == " +
                        ContactsContract.Contacts.IN_VISIBLE_GROUP + " AND " +
                        ContactsContract.Contacts.DISPLAY_NAME + " NOT LIKE '%@%'";
                Cursor cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, filter, null, null);
                DBHelper.insertArrayList(db,"Contacts",DBHelper.cursorToArrayList(cur));
                Log.d("ManageFriends","getContacts End");
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    thread.run();
}

Note: I'm aware of the big reason this process is slow - I'm converting the cursor result to an ArrayList < ArrayList < String>> and then inserting it into a SQLite db. But if I could get it to work in the background I'd be happy.

Was it helpful?

Solution

Consider using a daemon thread.

Daemon threads are typically used to perform services for your application/applet (such as loading the "fiddley bits"). The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution.

P.S. It is a low priority thread

Sources:

Example

Thread thread = new Thread();

thread.setDaemon(true);

thread.start();

EDIT!

Check out this link for AsyncTask which is a thread for UI background tasks.

OTHER TIPS

Consider using CursorLoader which loads data from ContentProvider in the background thread: Retrieving a List of Contacts

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top