RootScanner.java revision f83ccbd7edd32e728785fb7aad44f11886e79645
1/*
2 * Copyright (C) 2016 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.mtp;
18
19import android.content.ContentResolver;
20import android.net.Uri;
21import android.os.Process;
22import android.provider.DocumentsContract;
23import android.util.Log;
24
25import java.util.concurrent.CountDownLatch;
26import java.util.concurrent.ExecutorService;
27import java.util.concurrent.Executors;
28import java.util.concurrent.FutureTask;
29import java.util.concurrent.TimeUnit;
30
31final class RootScanner {
32    /**
33     * Polling interval in milliseconds used for first SHORT_POLLING_TIMES because it is more
34     * likely to add new root just after the device is added.
35     */
36    private final static long SHORT_POLLING_INTERVAL = 2000;
37
38    /**
39     * Polling interval in milliseconds for low priority polling, when changes are not expected.
40     */
41    private final static long LONG_POLLING_INTERVAL = 30 * 1000;
42
43    /**
44     * @see #SHORT_POLLING_INTERVAL
45     */
46    private final static long SHORT_POLLING_TIMES = 10;
47
48    /**
49     * Milliseconds we wait for background thread when pausing.
50     */
51    private final static long AWAIT_TERMINATION_TIMEOUT = 2000;
52
53    final ContentResolver mResolver;
54    final MtpManager mManager;
55    final MtpDatabase mDatabase;
56
57    ExecutorService mExecutor;
58    FutureTask<Void> mCurrentTask;
59
60    RootScanner(
61            ContentResolver resolver,
62            MtpManager manager,
63            MtpDatabase database) {
64        mResolver = resolver;
65        mManager = manager;
66        mDatabase = database;
67    }
68
69    /**
70     * Notifies a change of the roots list via ContentResolver.
71     */
72    void notifyChange() {
73        final Uri uri =
74                DocumentsContract.buildRootsUri(MtpDocumentsProvider.AUTHORITY);
75        mResolver.notifyChange(uri, null, false);
76    }
77
78    /**
79     * Starts to check new changes right away.
80     */
81    synchronized CountDownLatch resume() {
82        if (mExecutor == null) {
83            // Only single thread updates the database.
84            mExecutor = Executors.newSingleThreadExecutor();
85        }
86        if (mCurrentTask != null) {
87            // Cancel previous task.
88            mCurrentTask.cancel(true);
89        }
90        final UpdateRootsRunnable runnable = new UpdateRootsRunnable();
91        mCurrentTask = new FutureTask<Void>(runnable, null);
92        mExecutor.submit(mCurrentTask);
93        return runnable.mFirstScanCompleted;
94    }
95
96    /**
97     * Stops background thread and wait for its termination.
98     * @throws InterruptedException
99     */
100    synchronized void pause() throws InterruptedException {
101        if (mExecutor == null) {
102            return;
103        }
104        mExecutor.shutdownNow();
105        if (!mExecutor.awaitTermination(AWAIT_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS)) {
106            Log.e(MtpDocumentsProvider.TAG, "Failed to terminate RootScanner's background thread.");
107        }
108        mExecutor = null;
109    }
110
111    /**
112     * Runnable to scan roots and update the database information.
113     */
114    private final class UpdateRootsRunnable implements Runnable {
115        final CountDownLatch mFirstScanCompleted = new CountDownLatch(1);
116
117        @Override
118        public void run() {
119            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
120            int pollingCount = 0;
121            while (true) {
122                boolean changed = false;
123
124                // Update devices.
125                final MtpDeviceRecord[] devices = mManager.getDevices();
126                mDatabase.getMapper().startAddingDocuments(null /* parentDocumentId */);
127                for (final MtpDeviceRecord device : devices) {
128                    if (mDatabase.getMapper().putDeviceDocument(device)) {
129                        changed = true;
130                    }
131                }
132                if (mDatabase.getMapper().stopAddingDocuments(null /* parentDocumentId */)) {
133                    changed = true;
134                }
135
136                // Update roots.
137                for (final MtpDeviceRecord device : devices) {
138                    final String documentId = mDatabase.getDocumentIdForDevice(device.deviceId);
139                    if (documentId == null) {
140                        continue;
141                    }
142                    mDatabase.getMapper().startAddingDocuments(documentId);
143                    if (mDatabase.getMapper().putStorageDocuments(documentId, device.roots)) {
144                        changed = true;
145                    }
146                    if (mDatabase.getMapper().stopAddingDocuments(documentId)) {
147                        changed = true;
148                    }
149                }
150
151                if (changed) {
152                    notifyChange();
153                }
154                mFirstScanCompleted.countDown();
155                pollingCount++;
156                try {
157                    // Use SHORT_POLLING_PERIOD for the first SHORT_POLLING_TIMES because it is
158                    // more likely to add new root just after the device is added.
159                    // TODO: Use short interval only for a device that is just added.
160                    Thread.sleep(pollingCount > SHORT_POLLING_TIMES ?
161                        LONG_POLLING_INTERVAL : SHORT_POLLING_INTERVAL);
162                } catch (InterruptedException exp) {
163                    break;
164                }
165            }
166        }
167    }
168}
169