1 /* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.contacts.util; 18 19 import android.content.AsyncQueryHandler; 20 import android.content.Context; 21 import android.database.Cursor; 22 23 import java.lang.ref.WeakReference; 24 25 /** 26 * Slightly more abstract {@link AsyncQueryHandler} that helps keep a 27 * {@link WeakReference} back to a listener. Will properly close any 28 * {@link Cursor} if the listener ceases to exist. 29 * <p> 30 * This pattern can be used to perform background queries without leaking 31 * {@link Context} objects. 32 */ 33 public class NotifyingAsyncQueryHandler extends AsyncQueryHandler { 34 private WeakReference<AsyncQueryListener> mListener; 35 36 /** 37 * Interface to listen for completed query operations. 38 */ 39 public interface AsyncQueryListener { onQueryComplete(int token, Object cookie, Cursor cursor)40 void onQueryComplete(int token, Object cookie, Cursor cursor); 41 } 42 NotifyingAsyncQueryHandler(Context context, AsyncQueryListener listener)43 public NotifyingAsyncQueryHandler(Context context, AsyncQueryListener listener) { 44 super(context.getContentResolver()); 45 setQueryListener(listener); 46 } 47 48 /** 49 * Assign the given {@link AsyncQueryListener} to receive query events from 50 * asynchronous calls. Will replace any existing listener. 51 */ setQueryListener(AsyncQueryListener listener)52 public void setQueryListener(AsyncQueryListener listener) { 53 mListener = new WeakReference<AsyncQueryListener>(listener); 54 } 55 56 /** {@inheritDoc} */ 57 @Override onQueryComplete(int token, Object cookie, Cursor cursor)58 protected void onQueryComplete(int token, Object cookie, Cursor cursor) { 59 final AsyncQueryListener listener = mListener.get(); 60 if (listener != null) { 61 listener.onQueryComplete(token, cookie, cursor); 62 } else if (cursor != null) { 63 cursor.close(); 64 } 65 } 66 } 67