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 * @hide pending API council review 34 */ 35 public class NotifyingAsyncQueryHandler extends AsyncQueryHandler { 36 private WeakReference<AsyncQueryListener> mListener; 37 38 /** 39 * Interface to listen for completed query operations. 40 */ 41 public interface AsyncQueryListener { 42 void onQueryComplete(int token, Object cookie, Cursor cursor); 43 } 44 45 public NotifyingAsyncQueryHandler(Context context, AsyncQueryListener listener) { 46 super(context.getContentResolver()); 47 setQueryListener(listener); 48 } 49 50 /** 51 * Assign the given {@link AsyncQueryListener} to receive query events from 52 * asynchronous calls. Will replace any existing listener. 53 */ 54 public void setQueryListener(AsyncQueryListener listener) { 55 mListener = new WeakReference<AsyncQueryListener>(listener); 56 } 57 58 /** {@inheritDoc} */ 59 @Override 60 protected void onQueryComplete(int token, Object cookie, Cursor cursor) { 61 final AsyncQueryListener listener = mListener.get(); 62 if (listener != null) { 63 listener.onQueryComplete(token, cookie, cursor); 64 } else if (cursor != null) { 65 cursor.close(); 66 } 67 } 68 } 69