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 com.android.server.job.controllers;
18
19import java.io.PrintWriter;
20import java.util.ArrayList;
21
22import android.app.AlarmManager;
23import android.app.PendingIntent;
24import android.content.BroadcastReceiver;
25import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.os.SystemClock;
29import android.os.UserHandle;
30import android.util.Slog;
31
32import com.android.server.am.ActivityManagerService;
33import com.android.server.job.JobSchedulerService;
34import com.android.server.job.StateChangedListener;
35
36public class IdleController extends StateController {
37    private static final String TAG = "IdleController";
38
39    // Policy: we decide that we're "idle" if the device has been unused /
40    // screen off or dreaming for at least this long
41    private long mInactivityIdleThreshold;
42    private long mIdleWindowSlop;
43    final ArrayList<JobStatus> mTrackedTasks = new ArrayList<JobStatus>();
44    IdlenessTracker mIdleTracker;
45
46    // Singleton factory
47    private static Object sCreationLock = new Object();
48    private static volatile IdleController sController;
49
50    public static IdleController get(JobSchedulerService service) {
51        synchronized (sCreationLock) {
52            if (sController == null) {
53                sController = new IdleController(service, service.getContext(), service.getLock());
54            }
55            return sController;
56        }
57    }
58
59    private IdleController(StateChangedListener stateChangedListener, Context context,
60                Object lock) {
61        super(stateChangedListener, context, lock);
62        initIdleStateTracking();
63    }
64
65    /**
66     * StateController interface
67     */
68    @Override
69    public void maybeStartTrackingJobLocked(JobStatus taskStatus, JobStatus lastJob) {
70        if (taskStatus.hasIdleConstraint()) {
71            mTrackedTasks.add(taskStatus);
72            taskStatus.setIdleConstraintSatisfied(mIdleTracker.isIdle());
73        }
74    }
75
76    @Override
77    public void maybeStopTrackingJobLocked(JobStatus taskStatus, JobStatus incomingJob, boolean forUpdate) {
78        mTrackedTasks.remove(taskStatus);
79    }
80
81    /**
82     * Interaction with the task manager service
83     */
84    void reportNewIdleState(boolean isIdle) {
85        synchronized (mLock) {
86            for (JobStatus task : mTrackedTasks) {
87                task.setIdleConstraintSatisfied(isIdle);
88            }
89        }
90        mStateChangedListener.onControllerStateChanged();
91    }
92
93    /**
94     * Idle state tracking, and messaging with the task manager when
95     * significant state changes occur
96     */
97    private void initIdleStateTracking() {
98        mInactivityIdleThreshold = mContext.getResources().getInteger(
99                com.android.internal.R.integer.config_jobSchedulerInactivityIdleThreshold);
100        mIdleWindowSlop = mContext.getResources().getInteger(
101                com.android.internal.R.integer.config_jobSchedulerIdleWindowSlop);
102        mIdleTracker = new IdlenessTracker();
103        mIdleTracker.startTracking();
104    }
105
106    class IdlenessTracker extends BroadcastReceiver {
107        private AlarmManager mAlarm;
108        private PendingIntent mIdleTriggerIntent;
109        boolean mIdle;
110        boolean mScreenOn;
111
112        public IdlenessTracker() {
113            mAlarm = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
114
115            Intent intent = new Intent(ActivityManagerService.ACTION_TRIGGER_IDLE)
116                    .setPackage("android")
117                    .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
118            mIdleTriggerIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
119
120            // At boot we presume that the user has just "interacted" with the
121            // device in some meaningful way.
122            mIdle = false;
123            mScreenOn = true;
124        }
125
126        public boolean isIdle() {
127            return mIdle;
128        }
129
130        public void startTracking() {
131            IntentFilter filter = new IntentFilter();
132
133            // Screen state
134            filter.addAction(Intent.ACTION_SCREEN_ON);
135            filter.addAction(Intent.ACTION_SCREEN_OFF);
136
137            // Dreaming state
138            filter.addAction(Intent.ACTION_DREAMING_STARTED);
139            filter.addAction(Intent.ACTION_DREAMING_STOPPED);
140
141            // Debugging/instrumentation
142            filter.addAction(ActivityManagerService.ACTION_TRIGGER_IDLE);
143
144            mContext.registerReceiver(this, filter);
145        }
146
147        @Override
148        public void onReceive(Context context, Intent intent) {
149            final String action = intent.getAction();
150
151            if (action.equals(Intent.ACTION_SCREEN_ON)
152                    || action.equals(Intent.ACTION_DREAMING_STOPPED)) {
153                if (DEBUG) {
154                    Slog.v(TAG,"exiting idle : " + action);
155                }
156                mScreenOn = true;
157                //cancel the alarm
158                mAlarm.cancel(mIdleTriggerIntent);
159                if (mIdle) {
160                // possible transition to not-idle
161                    mIdle = false;
162                    reportNewIdleState(mIdle);
163                }
164            } else if (action.equals(Intent.ACTION_SCREEN_OFF)
165                    || action.equals(Intent.ACTION_DREAMING_STARTED)) {
166                // when the screen goes off or dreaming starts, we schedule the
167                // alarm that will tell us when we have decided the device is
168                // truly idle.
169                final long nowElapsed = SystemClock.elapsedRealtime();
170                final long when = nowElapsed + mInactivityIdleThreshold;
171                if (DEBUG) {
172                    Slog.v(TAG, "Scheduling idle : " + action + " now:" + nowElapsed + " when="
173                            + when);
174                }
175                mScreenOn = false;
176                mAlarm.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP,
177                        when, mIdleWindowSlop, mIdleTriggerIntent);
178            } else if (action.equals(ActivityManagerService.ACTION_TRIGGER_IDLE)) {
179                // idle time starts now. Do not set mIdle if screen is on.
180                if (!mIdle && !mScreenOn) {
181                    if (DEBUG) {
182                        Slog.v(TAG, "Idle trigger fired @ " + SystemClock.elapsedRealtime());
183                    }
184                    mIdle = true;
185                    reportNewIdleState(mIdle);
186                }
187            }
188        }
189    }
190
191    @Override
192    public void dumpControllerStateLocked(PrintWriter pw, int filterUid) {
193        pw.print("Idle: ");
194        pw.println(mIdleTracker.isIdle() ? "true" : "false");
195        pw.print("Tracking ");
196        pw.print(mTrackedTasks.size());
197        pw.println(":");
198        for (int i = 0; i < mTrackedTasks.size(); i++) {
199            final JobStatus js = mTrackedTasks.get(i);
200            if (!js.shouldDump(filterUid)) {
201                continue;
202            }
203            pw.print("  #");
204            js.printUniqueId(pw);
205            pw.print(" from ");
206            UserHandle.formatUid(pw, js.getSourceUid());
207            pw.println();
208        }
209    }
210}
211