2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package android.print;
19 import android.annotation.NonNull;
20 import android.content.Context;
21 import android.content.Loader;
22 import android.os.Handler;
23 import android.os.Message;
24 import android.printservice.PrintServiceInfo;
26 import java.util.List;
29 * Loader for the list of print services. Can be parametrized to select a subset.
33 public class PrintServicesLoader extends Loader<List<PrintServiceInfo>> {
34 /** What type of services to load. */
35 private final int mSelectionFlags;
37 /** The print manager to be used by this object */
38 private final @NonNull PrintManager mPrintManager;
40 /** Handler to sequentialize the delivery of the results to the main thread */
41 private Handler mHandler;
43 /** Listens for updates to the data from the platform */
44 private PrintManager.PrintServicesChangeListener mListener;
47 * Create a new PrintServicesLoader.
49 * @param selectionFlags What type of services to load.
51 public PrintServicesLoader(@NonNull PrintManager printManager, @NonNull Context context,
54 mPrintManager = printManager;
55 mSelectionFlags = selectionFlags;
59 protected void onForceLoad() {
64 * Read the print services and queue it to be delivered on the main thread.
66 private void queueNewResult() {
67 Message m = mHandler.obtainMessage(0);
68 m.obj = mPrintManager.getPrintServices(mSelectionFlags);
69 mHandler.sendMessage(m);
73 protected void onStartLoading() {
74 mHandler = new MyHandler();
75 mListener = new PrintManager.PrintServicesChangeListener() {
76 @Override public void onPrintServicesChanged() {
81 mPrintManager.addPrintServicesChangeListener(mListener);
83 // Immediately deliver a result
84 deliverResult(mPrintManager.getPrintServices(mSelectionFlags));
88 protected void onStopLoading() {
89 if (mListener != null) {
90 mPrintManager.removePrintServicesChangeListener(mListener);
94 if (mHandler != null) {
95 mHandler.removeMessages(0);
101 protected void onReset() {
106 * Handler to sequentialize all the updates to the main thread.
108 private class MyHandler extends Handler {
110 * Create a new handler on the main thread.
113 super(getContext().getMainLooper());
117 public void handleMessage(Message msg) {
118 super.handleMessage(msg);
121 deliverResult((List<PrintServiceInfo>) msg.obj);