01c51ebe11ac894090aa5da5f42f0508032a47ce
[zxing.git] / android / src / com / google / zxing / client / android / InactivityTimer.java
1 /*
2  * Copyright (C) 2010 ZXing authors
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
17 package com.google.zxing.client.android;
18
19 import java.util.concurrent.Executors;
20 import java.util.concurrent.ScheduledExecutorService;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.ThreadFactory;
23 import java.util.concurrent.TimeUnit;
24
25 import android.app.Activity;
26
27 /**
28  * Finishes an activity after a period of inactivity.
29  */
30 final class InactivityTimer {
31
32   private static final int INACTIVITY_DELAY_MINUTES = 3;
33
34   private final ScheduledExecutorService inactivityTimer =
35       Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory());
36   private final Activity activity;
37   private ScheduledFuture<?> inactivityFuture = null;
38
39   InactivityTimer(Activity activity) {
40     this.activity = activity;
41     onActivity();
42   }
43
44   void onActivity() {
45     cancel();
46     inactivityFuture = inactivityTimer.schedule(new FinishListener(activity),
47                                                 INACTIVITY_DELAY_MINUTES,
48                                                 TimeUnit.MINUTES);
49   }
50
51   private void cancel() {
52     if (inactivityFuture != null) {
53       inactivityFuture.cancel(true);
54       inactivityFuture = null;
55     }
56   }
57
58   void shutdown() {
59     cancel();
60     inactivityTimer.shutdown();
61   }
62
63   private static final class DaemonThreadFactory implements ThreadFactory {
64     public Thread newThread(Runnable runnable) {
65       Thread thread = new Thread(runnable);
66       thread.setDaemon(true);
67       return thread;
68     }
69   }
70
71 }