summaryrefslogtreecommitdiffstats
path: root/src/com/android/messaging/datamodel/action/ActionServiceImpl.java
blob: 6725dde2a1da5a47457febd028103fb16df2b1a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.messaging.datamodel.action;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;

import androidx.core.app.JobIntentService;

import com.android.messaging.Factory;
import com.android.messaging.datamodel.DataModel;
import com.android.messaging.util.ConnectivityUtil;
import com.android.messaging.util.LogUtil;
import com.android.messaging.util.LoggingTimer;
import com.google.common.annotations.VisibleForTesting;

/**
 * ActionService used to perform background processing for data model
 */
public class ActionServiceImpl extends JobIntentService {
    private static final String TAG = LogUtil.BUGLE_DATAMODEL_TAG;
    private static final boolean VERBOSE = false;

    /**
     * Unique job ID for this service.
     */
    public static final int JOB_ID = 1000;

    public ActionServiceImpl() {
        super();
    }

    /**
     * Start action by sending intent to the service
     * @param action - action to start
     */
    protected static void startAction(final Action action) {
        final Intent intent = makeIntent(OP_START_ACTION);
        final Bundle actionBundle = new Bundle();
        actionBundle.putParcelable(BUNDLE_ACTION, action);
        intent.putExtra(EXTRA_ACTION_BUNDLE, actionBundle);
        action.markStart();
        startServiceWithIntent(intent);
    }

    /**
     * Schedule an action to run after specified delay using alarm manager to send pendingintent
     * @param action - action to start
     * @param requestCode - request code used to collapse requests
     * @param delayMs - delay in ms (from now) before action will start
     */
    protected static void scheduleAction(final Action action, final int requestCode,
            final long delayMs) {
        final Intent intent = PendingActionReceiver.makeIntent(OP_START_ACTION);
        final Bundle actionBundle = new Bundle();
        actionBundle.putParcelable(BUNDLE_ACTION, action);
        intent.putExtra(EXTRA_ACTION_BUNDLE, actionBundle);

        PendingActionReceiver.scheduleAlarm(intent, requestCode, delayMs);
    }

    /**
     * Handle response returned by BackgroundWorker
     * @param request - request generating response
     * @param response - response from service
     */
    protected static void handleResponseFromBackgroundWorker(final Action action,
            final Bundle response) {
        final Intent intent = makeIntent(OP_RECEIVE_BACKGROUND_RESPONSE);

        final Bundle actionBundle = new Bundle();
        actionBundle.putParcelable(BUNDLE_ACTION, action);
        intent.putExtra(EXTRA_ACTION_BUNDLE, actionBundle);
        intent.putExtra(EXTRA_WORKER_RESPONSE, response);

        startServiceWithIntent(intent);
    }

    /**
     * Handle response returned by BackgroundWorker
     * @param request - request generating failure
     */
    protected static void handleFailureFromBackgroundWorker(final Action action,
            final Exception exception) {
        final Intent intent = makeIntent(OP_RECEIVE_BACKGROUND_FAILURE);

        final Bundle actionBundle = new Bundle();
        actionBundle.putParcelable(BUNDLE_ACTION, action);
        intent.putExtra(EXTRA_ACTION_BUNDLE, actionBundle);
        intent.putExtra(EXTRA_WORKER_EXCEPTION, exception);

        startServiceWithIntent(intent);
    }

    // ops
    @VisibleForTesting
    protected static final int OP_START_ACTION = 200;
    @VisibleForTesting
    protected static final int OP_RECEIVE_BACKGROUND_RESPONSE = 201;
    @VisibleForTesting
    protected static final int OP_RECEIVE_BACKGROUND_FAILURE = 202;

    // extras
    @VisibleForTesting
    protected static final String EXTRA_OP_CODE = "op";
    @VisibleForTesting
    protected static final String EXTRA_ACTION_BUNDLE = "datamodel_action_bundle";
    @VisibleForTesting
    protected static final String EXTRA_WORKER_EXCEPTION = "worker_exception";
    @VisibleForTesting
    protected static final String EXTRA_WORKER_RESPONSE = "worker_response";
    @VisibleForTesting
    protected static final String EXTRA_WORKER_UPDATE = "worker_update";
    @VisibleForTesting
    protected static final String BUNDLE_ACTION = "bundle_action";

    private BackgroundWorker mBackgroundWorker;
    private ConnectivityUtil mConnectivityUtil;

    /**
     * Allocate an intent with a specific opcode.
     */
    private static Intent makeIntent(final int opcode) {
        final Intent intent = new Intent(Factory.get().getApplicationContext(),
                ActionServiceImpl.class);
        intent.putExtra(EXTRA_OP_CODE, opcode);
        return intent;
    }

    /**
     * Broadcast receiver for alarms scheduled through ActionService.
     */
    public static class PendingActionReceiver extends BroadcastReceiver {
        static final String ACTION = "com.android.messaging.datamodel.PENDING_ACTION";

        /**
         * Allocate an intent with a specific opcode and alarm action.
         */
        public static Intent makeIntent(final int opcode) {
            final Intent intent = new Intent(Factory.get().getApplicationContext(),
                    PendingActionReceiver.class);
            intent.setAction(ACTION);
            intent.putExtra(EXTRA_OP_CODE, opcode);
            return intent;
        }

        public static void scheduleAlarm(final Intent intent, final int requestCode,
                final long delayMs) {
            final Context context = Factory.get().getApplicationContext();
            final PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);

            final AlarmManager mgr =
                    (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

            if (delayMs < Long.MAX_VALUE) {
                mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime() + delayMs, pendingIntent);
            } else {
                mgr.cancel(pendingIntent);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void onReceive(final Context context, final Intent intent) {
            ActionServiceImpl.startServiceWithIntent(intent);
        }
    }

    /**
     * Creates a pending intent that will trigger a data model action when the intent is
     * triggered
     */
    public static PendingIntent makeStartActionPendingIntent(final Context context,
            final Action action, final int requestCode, final boolean launchesAnActivity) {
        final Intent intent = PendingActionReceiver.makeIntent(OP_START_ACTION);
        final Bundle actionBundle = new Bundle();
        actionBundle.putParcelable(BUNDLE_ACTION, action);
        intent.putExtra(EXTRA_ACTION_BUNDLE, actionBundle);
        if (launchesAnActivity) {
            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        }
        return PendingIntent.getBroadcast(context, requestCode, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onCreate() {
        super.onCreate();
        mBackgroundWorker = DataModel.get().getBackgroundWorkerForActionService();
        mConnectivityUtil = DataModel.get().getConnectivityUtil();
        mConnectivityUtil.registerForSignalStrength();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mConnectivityUtil.unregisterForSignalStrength();
    }

    /**
     * Queue intent to the ActionService.
     */
    private static void startServiceWithIntent(final Intent intent) {
        final Context context = Factory.get().getApplicationContext();
        final int opcode = intent.getIntExtra(EXTRA_OP_CODE, 0);
        intent.setClass(context, ActionServiceImpl.class);
        enqueueWork(context, intent);
    }

    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, ActionServiceImpl.class, JOB_ID, work);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onHandleWork(final Intent intent) {
        if (intent == null) {
            // Shouldn't happen but sometimes does following another crash.
            LogUtil.w(TAG, "ActionService.onHandleIntent: Called with null intent");
            return;
        }
        final int opcode = intent.getIntExtra(EXTRA_OP_CODE, 0);

        Action action;
        final Bundle actionBundle = intent.getBundleExtra(EXTRA_ACTION_BUNDLE);
        actionBundle.setClassLoader(getClassLoader());
        switch(opcode) {
            case OP_START_ACTION: {
                action = (Action) actionBundle.getParcelable(BUNDLE_ACTION);
                executeAction(action);
                break;
            }

            case OP_RECEIVE_BACKGROUND_RESPONSE: {
                action = (Action) actionBundle.getParcelable(BUNDLE_ACTION);
                final Bundle response = intent.getBundleExtra(EXTRA_WORKER_RESPONSE);
                processBackgroundResponse(action, response);
                break;
            }

            case OP_RECEIVE_BACKGROUND_FAILURE: {
                action = (Action) actionBundle.getParcelable(BUNDLE_ACTION);
                processBackgroundFailure(action);
                break;
            }

            default:
                throw new RuntimeException("Unrecognized opcode in ActionServiceImpl");
        }

        action.sendBackgroundActions(mBackgroundWorker);
    }

    private static final long EXECUTION_TIME_WARN_LIMIT_MS = 1000; // 1 second
    /**
     * Local execution of action on ActionService thread
     */
    private void executeAction(final Action action) {
        action.markBeginExecute();

        final LoggingTimer timer = createLoggingTimer(action, "#executeAction");
        timer.start();

        final Object result = action.executeAction();

        timer.stopAndLog();

        action.markEndExecute(result);
    }

    /**
     * Process response on ActionService thread
     */
    private void processBackgroundResponse(final Action action, final Bundle response) {
        final LoggingTimer timer = createLoggingTimer(action, "#processBackgroundResponse");
        timer.start();

        action.processBackgroundWorkResponse(response);

        timer.stopAndLog();
    }

    /**
     * Process failure on ActionService thread
     */
    private void processBackgroundFailure(final Action action) {
        final LoggingTimer timer = createLoggingTimer(action, "#processBackgroundFailure");
        timer.start();

        action.processBackgroundWorkFailure();

        timer.stopAndLog();
    }

    private static LoggingTimer createLoggingTimer(
            final Action action, final String methodName) {
        return new LoggingTimer(TAG, action.getClass().getSimpleName() + methodName,
                EXECUTION_TIME_WARN_LIMIT_MS);
    }
}