1/*
2 * Copyright (C) 2013 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
17package android.printservice;
18
19import android.R;
20import android.app.Service;
21import android.content.ComponentName;
22import android.content.Context;
23import android.content.Intent;
24import android.os.Handler;
25import android.os.IBinder;
26import android.os.Looper;
27import android.os.Message;
28import android.os.RemoteException;
29import android.print.PrintJobInfo;
30import android.print.PrinterId;
31import android.util.Log;
32
33import java.util.ArrayList;
34import java.util.Collections;
35import java.util.List;
36
37/**
38 * <p>
39 * This is the base class for implementing print services. A print service knows
40 * how to discover and interact one or more printers via one or more protocols.
41 * </p>
42 * <h3>Printer discovery</h3>
43 * <p>
44 * A print service is responsible for discovering printers, adding discovered printers,
45 * removing added printers, and updating added printers. When the system is interested
46 * in printers managed by your service it will call {@link
47 * #onCreatePrinterDiscoverySession()} from which you must return a new {@link
48 * PrinterDiscoverySession} instance. The returned session encapsulates the interaction
49 * between the system and your service during printer discovery. For description of this
50 * interaction refer to the documentation for {@link PrinterDiscoverySession}.
51 * </p>
52 * <p>
53 * For every printer discovery session all printers have to be added since system does
54 * not retain printers across sessions. Hence, each printer known to this print service
55 * should be added only once during a discovery session. Only an already added printer
56 * can be removed or updated. Removed printers can be added again.
57 * </p>
58 * <h3>Print jobs</h3>
59 * <p>
60 * When a new print job targeted to a printer managed by this print service is is queued,
61 * i.e. ready for processing by the print service, you will receive a call to {@link
62 * #onPrintJobQueued(PrintJob)}. The print service may handle the print job immediately
63 * or schedule that for an appropriate time in the future. The list of all active print
64 * jobs for this service is obtained by calling {@link #getActivePrintJobs()}. Active
65 * print jobs are ones that are queued or started.
66 * </p>
67 * <p>
68 * A print service is responsible for setting a print job's state as appropriate
69 * while processing it. Initially, a print job is queued, i.e. {@link PrintJob#isQueued()
70 * PrintJob.isQueued()} returns true, which means that the document to be printed is
71 * spooled by the system and the print service can begin processing it. You can obtain
72 * the printed document by calling {@link PrintJob#getDocument() PrintJob.getDocument()}
73 * whose data is accessed via {@link PrintDocument#getData() PrintDocument.getData()}.
74 * After the print service starts printing the data it should set the print job's
75 * state to started by calling {@link PrintJob#start()} after which
76 * {@link PrintJob#isStarted() PrintJob.isStarted()} would return true. Upon successful
77 * completion, the print job should be marked as completed by calling {@link
78 * PrintJob#complete() PrintJob.complete()} after which {@link PrintJob#isCompleted()
79 * PrintJob.isCompleted()} would return true. In case of a failure, the print job should
80 * be marked as failed by calling {@link PrintJob#fail(String) PrintJob.fail(
81 * String)} after which {@link PrintJob#isFailed() PrintJob.isFailed()} would
82 * return true.
83 * </p>
84 * <p>
85 * If a print job is queued or started and the user requests to cancel it, the print
86 * service will receive a call to {@link #onRequestCancelPrintJob(PrintJob)} which
87 * requests from the service to do best effort in canceling the job. In case the job
88 * is successfully canceled, its state has to be marked as cancelled by calling {@link
89 * PrintJob#cancel() PrintJob.cancel()} after which {@link PrintJob#isCancelled()
90 * PrintJob.isCacnelled()} would return true.
91 * </p>
92 * <h3>Lifecycle</h3>
93 * <p>
94 * The lifecycle of a print service is managed exclusively by the system and follows
95 * the established service lifecycle. Additionally, starting or stopping a print service
96 * is triggered exclusively by an explicit user action through enabling or disabling it
97 * in the device settings. After the system binds to a print service, it calls {@link
98 * #onConnected()}. This method can be overriden by clients to perform post binding setup.
99 * Also after the system unbinds from a print service, it calls {@link #onDisconnected()}.
100 * This method can be overriden by clients to perform post unbinding cleanup. Your should
101 * not do any work after the system disconnected from your print service since the
102 * service can be killed at any time to reclaim memory. The system will not disconnect
103 * from a print service if there are active print jobs for the printers managed by it.
104 * </p>
105 * <h3>Declaration</h3>
106 * <p>
107 * A print service is declared as any other service in an AndroidManifest.xml but it must
108 * also specify that it handles the {@link android.content.Intent} with action {@link
109 * #SERVICE_INTERFACE android.printservice.PrintService}. Failure to declare this intent
110 * will cause the system to ignore the print service. Additionally, a print service must
111 * request the {@link android.Manifest.permission#BIND_PRINT_SERVICE
112 * android.permission.BIND_PRINT_SERVICE} permission to ensure that only the system can
113 * bind to it. Failure to declare this intent will cause the system to ignore the print
114 * service. Following is an example declaration:
115 * </p>
116 * <pre>
117 * &lt;service android:name=".MyPrintService"
118 *         android:permission="android.permission.BIND_PRINT_SERVICE"&gt;
119 *     &lt;intent-filter&gt;
120 *         &lt;action android:name="android.printservice.PrintService" /&gt;
121 *     &lt;/intent-filter&gt;
122 *     . . .
123 * &lt;/service&gt;
124 * </pre>
125 * <h3>Configuration</h3>
126 * <p>
127 * A print service can be configured by specifying an optional settings activity which
128 * exposes service specific settings, an optional add printers activity which is used for
129 * manual addition of printers, vendor name ,etc. It is a responsibility of the system
130 * to launch the settings and add printers activities when appropriate.
131 * </p>
132 * <p>
133 * A print service is configured by providing a {@link #SERVICE_META_DATA meta-data}
134 * entry in the manifest when declaring the service. A service declaration with a meta-data
135 * tag is presented below:
136 * <pre> &lt;service android:name=".MyPrintService"
137 *         android:permission="android.permission.BIND_PRINT_SERVICE"&gt;
138 *     &lt;intent-filter&gt;
139 *         &lt;action android:name="android.printservice.PrintService" /&gt;
140 *     &lt;/intent-filter&gt;
141 *     &lt;meta-data android:name="android.printservice" android:resource="@xml/printservice" /&gt;
142 * &lt;/service&gt;</pre>
143 * </p>
144 * <p>
145 * For more details for how to configure your print service via the meta-data refer to
146 * {@link #SERVICE_META_DATA} and <code>&lt;{@link android.R.styleable#PrintService
147 * print-service}&gt;</code>.
148 * </p>
149 * <p>
150 * <strong>Note: </strong> All callbacks in this class are executed on the main
151 * application thread. You should also invoke any method of this class on the main
152 * application thread.
153 * </p>
154 */
155public abstract class PrintService extends Service {
156
157    private static final String LOG_TAG = "PrintService";
158
159    private static final boolean DEBUG = false;
160
161    /**
162     * The {@link Intent} action that must be declared as handled by a service
163     * in its manifest for the system to recognize it as a print service.
164     */
165    public static final String SERVICE_INTERFACE = "android.printservice.PrintService";
166
167    /**
168     * Name under which a {@link PrintService} component publishes additional information
169     * about itself. This meta-data must reference a XML resource containing a <code>
170     * &lt;{@link android.R.styleable#PrintService print-service}&gt;</code> tag. This is
171     * a sample XML file configuring a print service:
172     * <pre> &lt;print-service
173     *     android:vendor="SomeVendor"
174     *     android:settingsActivity="foo.bar.MySettingsActivity"
175     *     andorid:addPrintersActivity="foo.bar.MyAddPrintersActivity."
176     *     . . .
177     * /&gt;</pre>
178     * <p>
179     * For detailed configuration options that can be specified via the meta-data
180     * refer to {@link android.R.styleable#PrintService android.R.styleable.PrintService}.
181     * </p>
182     * <p>
183     * If you declare a settings or add a printers activity, they have to be exported,
184     * by setting the {@link android.R.attr#exported} activity attribute to <code>true
185     * </code>. Also in case you want only the system to be able to start any of these
186     * activities you can specify that they request the android.permission
187     * .START_PRINT_SERVICE_CONFIG_ACTIVITY permission by setting the
188     * {@link android.R.attr#permission} activity attribute.
189     * </p>
190     */
191    public static final String SERVICE_META_DATA = "android.printservice";
192
193    /**
194     * If you declared an optional activity with advanced print options via the
195     * {@link R.attr#advancedPrintOptionsActivity advancedPrintOptionsActivity}
196     * attribute, this extra is used to pass in the currently constructed {@link
197     * PrintJobInfo} to your activity allowing you to modify it. After you are
198     * done, you must return the modified {@link PrintJobInfo} via the same extra.
199     * <p>
200     * You cannot modify the passed in {@link PrintJobInfo} directly, rather you
201     * should build another one using the {@link PrintJobInfo.Builder} class. You
202     * can specify any standard properties and add advanced, printer specific,
203     * ones via {@link PrintJobInfo.Builder#putAdvancedOption(String, String)
204     * PrintJobInfo.Builder#putAdvancedOption(String, String)} and {@link
205     * PrintJobInfo.Builder#putAdvancedOption(String, int)
206     * PrintJobInfo.Builder#putAdvancedOption(String, int)}. The advanced options
207     * are not interpreted by the system, they will not be visible to applications,
208     * and can only be accessed by your print service via {@link
209     * PrintJob#getAdvancedStringOption(String) PrintJob.getAdvancedStringOption(String)}
210     * and {@link PrintJob#getAdvancedIntOption(String) PrintJob.getAdvancedIntOption(String)}.
211     * </p>
212     */
213    public static final String EXTRA_PRINT_JOB_INFO = "android.intent.extra.print.PRINT_JOB_INFO";
214
215    private Handler mHandler;
216
217    private IPrintServiceClient mClient;
218
219    private int mLastSessionId = -1;
220
221    private PrinterDiscoverySession mDiscoverySession;
222
223    @Override
224    protected final void attachBaseContext(Context base) {
225        super.attachBaseContext(base);
226        mHandler = new ServiceHandler(base.getMainLooper());
227    }
228
229    /**
230     * The system has connected to this service.
231     */
232    protected void onConnected() {
233        /* do nothing */
234    }
235
236    /**
237     * The system has disconnected from this service.
238     */
239    protected void onDisconnected() {
240        /* do nothing */
241    }
242
243    /**
244     * Callback asking you to create a new {@link PrinterDiscoverySession}.
245     *
246     * @see PrinterDiscoverySession
247     */
248    protected abstract PrinterDiscoverySession onCreatePrinterDiscoverySession();
249
250    /**
251     * Called when cancellation of a print job is requested. The service
252     * should do best effort to fulfill the request. After the cancellation
253     * is performed, the print job should be marked as cancelled state by
254     * calling {@link PrintJob#cancel()}.
255     *
256     * @param printJob The print job to cancel.
257     *
258     * @see PrintJob#cancel() PrintJob.cancel()
259     * @see PrintJob#isCancelled() PrintJob.isCancelled()
260     */
261    protected abstract void onRequestCancelPrintJob(PrintJob printJob);
262
263    /**
264     * Called when there is a queued print job for one of the printers
265     * managed by this print service.
266     *
267     * @param printJob The new queued print job.
268     *
269     * @see PrintJob#isQueued() PrintJob.isQueued()
270     * @see #getActivePrintJobs()
271     */
272    protected abstract void onPrintJobQueued(PrintJob printJob);
273
274    /**
275     * Gets the active print jobs for the printers managed by this service.
276     * Active print jobs are ones that are not in a final state, i.e. whose
277     * state is queued or started.
278     *
279     * @return The active print jobs.
280     *
281     * @see PrintJob#isQueued() PrintJob.isQueued()
282     * @see PrintJob#isStarted() PrintJob.isStarted()
283     */
284    public final List<PrintJob> getActivePrintJobs() {
285        throwIfNotCalledOnMainThread();
286        if (mClient == null) {
287            return Collections.emptyList();
288        }
289        try {
290            List<PrintJob> printJobs = null;
291            List<PrintJobInfo> printJobInfos = mClient.getPrintJobInfos();
292            if (printJobInfos != null) {
293                final int printJobInfoCount = printJobInfos.size();
294                printJobs = new ArrayList<PrintJob>(printJobInfoCount);
295                for (int i = 0; i < printJobInfoCount; i++) {
296                    printJobs.add(new PrintJob(printJobInfos.get(i), mClient));
297                }
298            }
299            if (printJobs != null) {
300                return printJobs;
301            }
302        } catch (RemoteException re) {
303            Log.e(LOG_TAG, "Error calling getPrintJobs()", re);
304        }
305        return Collections.emptyList();
306    }
307
308    /**
309     * Generates a global printer id given the printer's locally unique one.
310     *
311     * @param localId A locally unique id in the context of your print service.
312     * @return Global printer id.
313     */
314    public final PrinterId generatePrinterId(String localId) {
315        throwIfNotCalledOnMainThread();
316        return new PrinterId(new ComponentName(getPackageName(),
317                getClass().getName()), localId);
318    }
319
320    static void throwIfNotCalledOnMainThread() {
321        if (!Looper.getMainLooper().isCurrentThread()) {
322            throw new IllegalAccessError("must be called from the main thread");
323        }
324    }
325
326    @Override
327    public final IBinder onBind(Intent intent) {
328        return new IPrintService.Stub() {
329            @Override
330            public void createPrinterDiscoverySession() {
331                mHandler.sendEmptyMessage(ServiceHandler.MSG_CREATE_PRINTER_DISCOVERY_SESSION);
332            }
333
334            @Override
335            public void destroyPrinterDiscoverySession() {
336                mHandler.sendEmptyMessage(ServiceHandler.MSG_DESTROY_PRINTER_DISCOVERY_SESSION);
337            }
338
339            public void startPrinterDiscovery(List<PrinterId> priorityList) {
340                mHandler.obtainMessage(ServiceHandler.MSG_START_PRINTER_DISCOVERY,
341                        priorityList).sendToTarget();
342            }
343
344            @Override
345            public void stopPrinterDiscovery() {
346                mHandler.sendEmptyMessage(ServiceHandler.MSG_STOP_PRINTER_DISCOVERY);
347            }
348
349            @Override
350            public void validatePrinters(List<PrinterId> printerIds) {
351                mHandler.obtainMessage(ServiceHandler.MSG_VALIDATE_PRINTERS,
352                        printerIds).sendToTarget();
353            }
354
355            @Override
356            public void startPrinterStateTracking(PrinterId printerId) {
357                mHandler.obtainMessage(ServiceHandler.MSG_START_PRINTER_STATE_TRACKING,
358                        printerId).sendToTarget();
359            }
360
361            @Override
362            public void stopPrinterStateTracking(PrinterId printerId) {
363                mHandler.obtainMessage(ServiceHandler.MSG_STOP_PRINTER_STATE_TRACKING,
364                        printerId).sendToTarget();
365            }
366
367            @Override
368            public void setClient(IPrintServiceClient client) {
369                mHandler.obtainMessage(ServiceHandler.MSG_SET_CLEINT, client)
370                        .sendToTarget();
371            }
372
373            @Override
374            public void requestCancelPrintJob(PrintJobInfo printJobInfo) {
375                mHandler.obtainMessage(ServiceHandler.MSG_ON_REQUEST_CANCEL_PRINTJOB,
376                        printJobInfo).sendToTarget();
377            }
378
379            @Override
380            public void onPrintJobQueued(PrintJobInfo printJobInfo) {
381                mHandler.obtainMessage(ServiceHandler.MSG_ON_PRINTJOB_QUEUED,
382                        printJobInfo).sendToTarget();
383            }
384        };
385    }
386
387    private final class ServiceHandler extends Handler {
388        public static final int MSG_CREATE_PRINTER_DISCOVERY_SESSION = 1;
389        public static final int MSG_DESTROY_PRINTER_DISCOVERY_SESSION = 2;
390        public static final int MSG_START_PRINTER_DISCOVERY = 3;
391        public static final int MSG_STOP_PRINTER_DISCOVERY = 4;
392        public static final int MSG_VALIDATE_PRINTERS = 5;
393        public static final int MSG_START_PRINTER_STATE_TRACKING = 6;
394        public static final int MSG_STOP_PRINTER_STATE_TRACKING = 7;
395        public static final int MSG_ON_PRINTJOB_QUEUED = 8;
396        public static final int MSG_ON_REQUEST_CANCEL_PRINTJOB = 9;
397        public static final int MSG_SET_CLEINT = 10;
398
399        public ServiceHandler(Looper looper) {
400            super(looper, null, true);
401        }
402
403        @Override
404        @SuppressWarnings("unchecked")
405        public void handleMessage(Message message) {
406            final int action = message.what;
407            switch (action) {
408                case MSG_CREATE_PRINTER_DISCOVERY_SESSION: {
409                    if (DEBUG) {
410                        Log.i(LOG_TAG, "MSG_CREATE_PRINTER_DISCOVERY_SESSION "
411                                + getPackageName());
412                    }
413                    PrinterDiscoverySession session = onCreatePrinterDiscoverySession();
414                    if (session == null) {
415                        throw new NullPointerException("session cannot be null");
416                    }
417                    if (session.getId() == mLastSessionId) {
418                        throw new IllegalStateException("cannot reuse session instances");
419                    }
420                    mDiscoverySession = session;
421                    mLastSessionId = session.getId();
422                    session.setObserver(mClient);
423                } break;
424
425                case MSG_DESTROY_PRINTER_DISCOVERY_SESSION: {
426                    if (DEBUG) {
427                        Log.i(LOG_TAG, "MSG_DESTROY_PRINTER_DISCOVERY_SESSION "
428                                + getPackageName());
429                    }
430                    if (mDiscoverySession != null) {
431                        mDiscoverySession.destroy();
432                        mDiscoverySession = null;
433                    }
434                } break;
435
436                case MSG_START_PRINTER_DISCOVERY: {
437                    if (DEBUG) {
438                        Log.i(LOG_TAG, "MSG_START_PRINTER_DISCOVERY "
439                                + getPackageName());
440                    }
441                    if (mDiscoverySession != null) {
442                        List<PrinterId> priorityList = (ArrayList<PrinterId>) message.obj;
443                        mDiscoverySession.startPrinterDiscovery(priorityList);
444                    }
445                } break;
446
447                case MSG_STOP_PRINTER_DISCOVERY: {
448                    if (DEBUG) {
449                        Log.i(LOG_TAG, "MSG_STOP_PRINTER_DISCOVERY "
450                                + getPackageName());
451                    }
452                    if (mDiscoverySession != null) {
453                        mDiscoverySession.stopPrinterDiscovery();
454                    }
455                } break;
456
457                case MSG_VALIDATE_PRINTERS: {
458                    if (DEBUG) {
459                        Log.i(LOG_TAG, "MSG_VALIDATE_PRINTERS "
460                                + getPackageName());
461                    }
462                    if (mDiscoverySession != null) {
463                        List<PrinterId> printerIds = (List<PrinterId>) message.obj;
464                        mDiscoverySession.validatePrinters(printerIds);
465                    }
466                } break;
467
468                case MSG_START_PRINTER_STATE_TRACKING: {
469                    if (DEBUG) {
470                        Log.i(LOG_TAG, "MSG_START_PRINTER_STATE_TRACKING "
471                                + getPackageName());
472                    }
473                    if (mDiscoverySession != null) {
474                        PrinterId printerId = (PrinterId) message.obj;
475                        mDiscoverySession.startPrinterStateTracking(printerId);
476                    }
477                } break;
478
479                case MSG_STOP_PRINTER_STATE_TRACKING: {
480                    if (DEBUG) {
481                        Log.i(LOG_TAG, "MSG_STOP_PRINTER_STATE_TRACKING "
482                                + getPackageName());
483                    }
484                    if (mDiscoverySession != null) {
485                        PrinterId printerId = (PrinterId) message.obj;
486                        mDiscoverySession.stopPrinterStateTracking(printerId);
487                    }
488                } break;
489
490                case MSG_ON_REQUEST_CANCEL_PRINTJOB: {
491                    if (DEBUG) {
492                        Log.i(LOG_TAG, "MSG_ON_REQUEST_CANCEL_PRINTJOB "
493                                + getPackageName());
494                    }
495                    PrintJobInfo printJobInfo = (PrintJobInfo) message.obj;
496                    onRequestCancelPrintJob(new PrintJob(printJobInfo, mClient));
497                } break;
498
499                case MSG_ON_PRINTJOB_QUEUED: {
500                    if (DEBUG) {
501                        Log.i(LOG_TAG, "MSG_ON_PRINTJOB_QUEUED "
502                                + getPackageName());
503                    }
504                    PrintJobInfo printJobInfo = (PrintJobInfo) message.obj;
505                    if (DEBUG) {
506                        Log.i(LOG_TAG, "Queued: " + printJobInfo);
507                    }
508                    onPrintJobQueued(new PrintJob(printJobInfo, mClient));
509                } break;
510
511                case MSG_SET_CLEINT: {
512                    if (DEBUG) {
513                        Log.i(LOG_TAG, "MSG_SET_CLEINT "
514                                + getPackageName());
515                    }
516                    mClient = (IPrintServiceClient) message.obj;
517                    if (mClient != null) {
518                        onConnected();
519                     } else {
520                        onDisconnected();
521                     }
522                } break;
523
524                default: {
525                    throw new IllegalArgumentException("Unknown message: " + action);
526                }
527            }
528        }
529    }
530}
531