ConditionProviderService.java revision c279b996f13e644782633853612452860e596308
1/*
2 * Copyright (C) 2014 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.service.notification;
18
19import android.annotation.SdkConstant;
20import android.app.INotificationManager;
21import android.app.Service;
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.Intent;
25import android.net.Uri;
26import android.os.Handler;
27import android.os.IBinder;
28import android.os.Message;
29import android.os.ServiceManager;
30import android.util.Log;
31
32/**
33 * A service that provides conditions about boolean state.
34 * <p>To extend this class, you must declare the service in your manifest file with
35 * the {@link android.Manifest.permission#BIND_CONDITION_PROVIDER_SERVICE} permission
36 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. If you want users to be
37 * able to create and update conditions for this service to monitor, include the
38 * {@link #META_DATA_RULE_TYPE} and {@link #META_DATA_CONFIGURATION_ACTIVITY} tags and request the
39 * {@link android.Manifest.permission#ACCESS_NOTIFICATION_POLICY} permission. For example:</p>
40 * <pre>
41 * &lt;service android:name=".MyConditionProvider"
42 *          android:label="&#64;string/service_name"
43 *          android:permission="android.permission.BIND_CONDITION_PROVIDER_SERVICE">
44 *     &lt;intent-filter>
45 *         &lt;action android:name="android.service.notification.ConditionProviderService" />
46 *     &lt;/intent-filter>
47 *     &lt;meta-data
48 *               android:name="android.service.zen.automatic.ruleType"
49 *               android:value="@string/my_condition_rule">
50 *           &lt;/meta-data>
51 *           &lt;meta-data
52 *               android:name="android.service.zen.automatic.configurationActivity"
53 *               android:value="com.my.package/.MyConditionConfigurationActivity">
54 *           &lt;/meta-data>
55 * &lt;/service></pre>
56 *
57 */
58public abstract class ConditionProviderService extends Service {
59    private final String TAG = ConditionProviderService.class.getSimpleName()
60            + "[" + getClass().getSimpleName() + "]";
61
62    private final H mHandler = new H();
63
64    private Provider mProvider;
65    private INotificationManager mNoMan;
66
67    /**
68     * The {@link Intent} that must be declared as handled by the service.
69     */
70    @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
71    public static final String SERVICE_INTERFACE
72            = "android.service.notification.ConditionProviderService";
73
74    /**
75     * The name of the {@code meta-data} tag containing a localized name of the type of zen rules
76     * provided by this service.
77     */
78    public static final String META_DATA_RULE_TYPE = "android.service.zen.automatic.ruleType";
79
80    /**
81     * The name of the {@code meta-data} tag containing the {@link ComponentName} of an activity
82     * that allows users to configure the conditions provided by this service.
83     */
84    public static final String META_DATA_CONFIGURATION_ACTIVITY =
85            "android.service.zen.automatic.configurationActivity";
86
87    /**
88     * A String rule id extra passed to {@link #META_DATA_CONFIGURATION_ACTIVITY}.
89     */
90    public static final String EXTRA_RULE_ID = "android.content.automatic.ruleId";
91
92    /**
93     * Called when this service is connected.
94     */
95    abstract public void onConnected();
96
97    /**
98     * Called when the system wants to know the state of Conditions managed by this provider.
99     *
100     * Implementations should evaluate the state of all subscribed conditions, and provide updates
101     * by calling {@link #notifyCondition(Condition)} or {@link #notifyConditions(Condition...)}.
102     * @param relevance
103     */
104    abstract public void onRequestConditions(int relevance);
105
106    /**
107     * Called by the system when there is a new {@link Condition} to be managed by this provider.
108     * @param conditionId the Uri describing the criteria of the condition.
109     */
110    abstract public void onSubscribe(Uri conditionId);
111
112    /**
113     * Called by the system when a {@link Condition} has been deleted.
114     * @param conditionId the Uri describing the criteria of the deleted condition.
115     */
116    abstract public void onUnsubscribe(Uri conditionId);
117
118    private final INotificationManager getNotificationInterface() {
119        if (mNoMan == null) {
120            mNoMan = INotificationManager.Stub.asInterface(
121                    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
122        }
123        return mNoMan;
124    }
125
126    /**
127     * Informs the notification manager that the state of a Condition has changed.
128     * @param condition the condition that has changed.
129     */
130    public final void notifyCondition(Condition condition) {
131        if (condition == null) return;
132        notifyConditions(new Condition[]{ condition });
133    }
134
135    /**
136     * Informs the notification manager that the state of one or more Conditions has changed.
137     * @param conditions the changed conditions.
138     */
139    public final void notifyConditions(Condition... conditions) {
140        if (!isBound() || conditions == null) return;
141        try {
142            getNotificationInterface().notifyConditions(getPackageName(), mProvider, conditions);
143        } catch (android.os.RemoteException ex) {
144            Log.v(TAG, "Unable to contact notification manager", ex);
145        }
146    }
147
148    @Override
149    public IBinder onBind(Intent intent) {
150        if (mProvider == null) {
151            mProvider = new Provider();
152        }
153        return mProvider;
154    }
155
156    private boolean isBound() {
157        if (mProvider == null) {
158            Log.w(TAG, "Condition provider service not yet bound.");
159            return false;
160        }
161        return true;
162    }
163
164    private final class Provider extends IConditionProvider.Stub {
165        @Override
166        public void onConnected() {
167            mHandler.obtainMessage(H.ON_CONNECTED).sendToTarget();
168        }
169
170        @Override
171        public void onRequestConditions(int relevance) {
172            mHandler.obtainMessage(H.ON_REQUEST_CONDITIONS, relevance, 0).sendToTarget();
173        }
174
175        @Override
176        public void onSubscribe(Uri conditionId) {
177            mHandler.obtainMessage(H.ON_SUBSCRIBE, conditionId).sendToTarget();
178        }
179
180        @Override
181        public void onUnsubscribe(Uri conditionId) {
182            mHandler.obtainMessage(H.ON_UNSUBSCRIBE, conditionId).sendToTarget();
183        }
184    }
185
186    private final class H extends Handler {
187        private static final int ON_CONNECTED = 1;
188        private static final int ON_REQUEST_CONDITIONS = 2;
189        private static final int ON_SUBSCRIBE = 3;
190        private static final int ON_UNSUBSCRIBE = 4;
191
192        @Override
193        public void handleMessage(Message msg) {
194            String name = null;
195            try {
196                switch(msg.what) {
197                    case ON_CONNECTED:
198                        name = "onConnected";
199                        onConnected();
200                        break;
201                    case ON_REQUEST_CONDITIONS:
202                        name = "onRequestConditions";
203                        onRequestConditions(msg.arg1);
204                        break;
205                    case ON_SUBSCRIBE:
206                        name = "onSubscribe";
207                        onSubscribe((Uri)msg.obj);
208                        break;
209                    case ON_UNSUBSCRIBE:
210                        name = "onUnsubscribe";
211                        onUnsubscribe((Uri)msg.obj);
212                        break;
213                }
214            } catch (Throwable t) {
215                Log.w(TAG, "Error running " + name, t);
216            }
217        }
218    }
219}
220