DeskClock.java revision e46be904bd76dff5a13aeef12e9bfeddac7bbe81
1/*
2 * Copyright (C) 2009 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.deskclock;
18
19import android.app.Activity;
20import android.app.AlarmManager;
21import android.app.AlertDialog;
22import android.app.PendingIntent;
23import android.content.BroadcastReceiver;
24import android.content.Context;
25import android.content.DialogInterface;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.SharedPreferences;
29import android.content.pm.PackageManager;
30import android.content.res.Configuration;
31import android.content.res.Resources;
32import android.database.ContentObserver;
33import android.database.Cursor;
34import android.graphics.Rect;
35import android.graphics.drawable.BitmapDrawable;
36import android.graphics.drawable.ColorDrawable;
37import android.graphics.drawable.Drawable;
38import android.net.Uri;
39import android.os.Bundle;
40import android.os.Handler;
41import android.os.Message;
42import android.os.SystemClock;
43import android.os.PowerManager;
44import android.provider.Settings;
45import android.text.TextUtils;
46import android.text.format.DateFormat;
47import android.util.DisplayMetrics;
48import android.util.Log;
49import android.view.ContextMenu.ContextMenuInfo;
50import android.view.ContextMenu;
51import android.view.LayoutInflater;
52import android.view.Menu;
53import android.view.MenuInflater;
54import android.view.MenuItem;
55import android.view.MotionEvent;
56import android.view.View.OnClickListener;
57import android.view.View.OnCreateContextMenuListener;
58import android.view.View;
59import android.view.ViewGroup;
60import android.view.ViewTreeObserver;
61import android.view.ViewTreeObserver.OnGlobalFocusChangeListener;
62import android.view.Window;
63import android.view.WindowManager;
64import android.view.animation.Animation;
65import android.view.animation.AnimationUtils;
66import android.view.animation.TranslateAnimation;
67import android.widget.AbsoluteLayout;
68import android.widget.AdapterView.AdapterContextMenuInfo;
69import android.widget.AdapterView.OnItemClickListener;
70import android.widget.AdapterView;
71import android.widget.Button;
72import android.widget.CheckBox;
73import android.widget.ImageButton;
74import android.widget.ImageView;
75import android.widget.TextView;
76
77import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
78import static android.os.BatteryManager.BATTERY_STATUS_FULL;
79import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
80
81import java.io.IOException;
82import java.io.InputStream;
83import java.util.Calendar;
84import java.util.Date;
85import java.util.Locale;
86import java.util.Random;
87
88/**
89 * DeskClock clock view for desk docks.
90 */
91public class DeskClock extends Activity {
92    private static final boolean DEBUG = false;
93
94    private static final String LOG_TAG = "DeskClock";
95
96    // Package ID of the music player.
97    private static final String MUSIC_PACKAGE_ID = "com.android.music";
98
99    // Alarm action for midnight (so we can update the date display).
100    private static final String ACTION_MIDNIGHT = "com.android.deskclock.MIDNIGHT";
101
102    // Interval between forced polls of the weather widget.
103    private final long QUERY_WEATHER_DELAY = 60 * 60 * 1000; // 1 hr
104
105    // Intent to broadcast for dock settings.
106    private static final String DOCK_SETTINGS_ACTION = "com.android.settings.DOCK_SETTINGS";
107
108    // Delay before engaging the burn-in protection mode (green-on-black).
109    private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min
110
111    // Repositioning delay in screen saver.
112    private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
113
114    // Color to use for text & graphics in screen saver mode.
115    private final int SCREEN_SAVER_COLOR = 0xFF308030;
116    private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018;
117
118    // Opacity of black layer between clock display and wallpaper.
119    private final float DIM_BEHIND_AMOUNT_NORMAL = 0.4f;
120    private final float DIM_BEHIND_AMOUNT_DIMMED = 0.8f; // higher contrast when display dimmed
121
122    // Internal message IDs.
123    private final int QUERY_WEATHER_DATA_MSG     = 0x1000;
124    private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
125    private final int SCREEN_SAVER_TIMEOUT_MSG   = 0x2000;
126    private final int SCREEN_SAVER_MOVE_MSG      = 0x2001;
127
128    // Weather widget query information.
129    private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
130    private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
131    private static final String WEATHER_CONTENT_PATH = "/weather/current";
132    private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
133            "location",
134            "timestamp",
135            "temperature",
136            "highTemperature",
137            "lowTemperature",
138            "iconUrl",
139            "iconResId",
140            "description",
141        };
142
143    private static final String ACTION_GENIE_REFRESH = "com.google.android.apps.genie.REFRESH";
144
145    // State variables follow.
146    private DigitalClock mTime;
147    private TextView mDate;
148
149    private TextView mNextAlarm = null;
150    private TextView mBatteryDisplay;
151
152    private TextView mWeatherCurrentTemperature;
153    private TextView mWeatherHighTemperature;
154    private TextView mWeatherLowTemperature;
155    private TextView mWeatherLocation;
156    private ImageView mWeatherIcon;
157
158    private String mWeatherCurrentTemperatureString;
159    private String mWeatherHighTemperatureString;
160    private String mWeatherLowTemperatureString;
161    private String mWeatherLocationString;
162    private Drawable mWeatherIconDrawable;
163
164    private Resources mGenieResources = null;
165
166    private boolean mDimmed = false;
167    private boolean mScreenSaverMode = false;
168
169    private String mDateFormat;
170
171    private int mBatteryLevel = -1;
172    private boolean mPluggedIn = false;
173
174    private boolean mLaunchedFromDock = false;
175
176    private Random mRNG;
177
178    private PendingIntent mMidnightIntent;
179
180    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
181        @Override
182        public void onReceive(Context context, Intent intent) {
183            final String action = intent.getAction();
184            if (DEBUG) Log.d(LOG_TAG, "mIntentReceiver.onReceive: action=" + action + ", intent=" + intent);
185            if (Intent.ACTION_DATE_CHANGED.equals(action) || ACTION_MIDNIGHT.equals(action)) {
186                refreshDate();
187            } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
188                handleBatteryUpdate(
189                    intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
190                    intent.getIntExtra("level", 0));
191            } else if (Intent.ACTION_DOCK_EVENT.equals(action)) {
192                int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, -1);
193                if (DEBUG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT, state=" + state);
194                if (state == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
195                    if (mLaunchedFromDock) {
196                        // moveTaskToBack(false);
197                        finish();
198                    }
199                    mLaunchedFromDock = false;
200                }
201            }
202        }
203    };
204
205    private final Handler mHandy = new Handler() {
206        @Override
207        public void handleMessage(Message m) {
208            if (m.what == QUERY_WEATHER_DATA_MSG) {
209                new Thread() { public void run() { queryWeatherData(); } }.start();
210                scheduleWeatherQueryDelayed(QUERY_WEATHER_DELAY);
211            } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
212                updateWeatherDisplay();
213            } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
214                saveScreen();
215            } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
216                moveScreenSaver();
217            }
218        }
219    };
220
221    private final ContentObserver mContentObserver = new ContentObserver(mHandy) {
222        @Override
223        public void onChange(boolean selfChange) {
224            if (DEBUG) Log.d(LOG_TAG, "content observer notified that weather changed");
225            refreshWeather();
226        }
227    };
228
229
230    private void moveScreenSaver() {
231        moveScreenSaverTo(-1,-1);
232    }
233    private void moveScreenSaverTo(int x, int y) {
234        if (!mScreenSaverMode) return;
235
236        final View saver_view = findViewById(R.id.saver_view);
237
238        DisplayMetrics metrics = new DisplayMetrics();
239        getWindowManager().getDefaultDisplay().getMetrics(metrics);
240
241        if (x < 0 || y < 0) {
242            int myWidth = saver_view.getMeasuredWidth();
243            int myHeight = saver_view.getMeasuredHeight();
244            x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
245            y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
246        }
247
248        if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
249                System.currentTimeMillis(), x, y));
250
251        saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams(
252            ViewGroup.LayoutParams.WRAP_CONTENT,
253            ViewGroup.LayoutParams.WRAP_CONTENT,
254            x,
255            y));
256
257        // Synchronize our jumping so that it happens exactly on the second.
258        mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
259            SCREEN_SAVER_MOVE_DELAY +
260            (1000 - (System.currentTimeMillis() % 1000)));
261    }
262
263    private void setWakeLock(boolean hold) {
264        if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
265        Window win = getWindow();
266        WindowManager.LayoutParams winParams = win.getAttributes();
267        winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
268        winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
269        winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
270        if (hold)
271            winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
272        else
273            winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
274        win.setAttributes(winParams);
275    }
276
277    private void scheduleScreenSaver() {
278        // reschedule screen saver
279        mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
280        mHandy.sendMessageDelayed(
281            Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG),
282            SCREEN_SAVER_TIMEOUT);
283    }
284
285    private void restoreScreen() {
286        if (!mScreenSaverMode) return;
287        if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
288        mScreenSaverMode = false;
289        initViews();
290        doDim(false); // restores previous dim mode
291        // policy: update weather info when returning from screen saver
292        if (mPluggedIn) requestWeatherDataFetch();
293
294        scheduleScreenSaver();
295
296        refreshAll();
297    }
298
299    // Special screen-saver mode for OLED displays that burn in quickly
300    private void saveScreen() {
301        if (mScreenSaverMode) return;
302        if (DEBUG) Log.d(LOG_TAG, "saveScreen");
303
304        // quickly stash away the x/y of the current date
305        final View oldTimeDate = findViewById(R.id.time_date);
306        int oldLoc[] = new int[2];
307        oldTimeDate.getLocationOnScreen(oldLoc);
308
309        mScreenSaverMode = true;
310        Window win = getWindow();
311        WindowManager.LayoutParams winParams = win.getAttributes();
312        winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
313        win.setAttributes(winParams);
314
315        // give up any internal focus before we switch layouts
316        final View focused = getCurrentFocus();
317        if (focused != null) focused.clearFocus();
318
319        setContentView(R.layout.desk_clock_saver);
320
321        mTime = (DigitalClock) findViewById(R.id.time);
322        mDate = (TextView) findViewById(R.id.date);
323        mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
324
325        final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
326
327        ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
328        ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
329        mDate.setTextColor(color);
330        mNextAlarm.setTextColor(color);
331        mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
332            getResources().getDrawable(mDimmed
333                ? R.drawable.ic_lock_idle_alarm_saver_dim
334                : R.drawable.ic_lock_idle_alarm_saver),
335            null, null, null);
336
337        mBatteryDisplay =
338        mWeatherCurrentTemperature =
339        mWeatherHighTemperature =
340        mWeatherLowTemperature =
341        mWeatherLocation = null;
342        mWeatherIcon = null;
343
344        refreshDate();
345        refreshAlarm();
346
347        moveScreenSaverTo(oldLoc[0], oldLoc[1]);
348    }
349
350    @Override
351    public void onUserInteraction() {
352        if (mScreenSaverMode)
353            restoreScreen();
354    }
355
356    // Tell the Genie widget to load new data from the network.
357    private void requestWeatherDataFetch() {
358        if (DEBUG) Log.d(LOG_TAG, "forcing the Genie widget to update weather now...");
359        sendBroadcast(new Intent(ACTION_GENIE_REFRESH).putExtra("requestWeather", true));
360        // we expect the result to show up in our content observer
361    }
362
363    private boolean supportsWeather() {
364        return (mGenieResources != null);
365    }
366
367    private void scheduleWeatherQueryDelayed(long delay) {
368        // cancel any existing scheduled queries
369        unscheduleWeatherQuery();
370
371        if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
372
373        mHandy.sendEmptyMessageDelayed(QUERY_WEATHER_DATA_MSG, delay);
374    }
375
376    private void unscheduleWeatherQuery() {
377        mHandy.removeMessages(QUERY_WEATHER_DATA_MSG);
378    }
379
380    private void queryWeatherData() {
381        // if we couldn't load the weather widget's resources, we simply
382        // assume it's not present on the device.
383        if (mGenieResources == null) return;
384
385        Uri queryUri = new Uri.Builder()
386            .scheme(android.content.ContentResolver.SCHEME_CONTENT)
387            .authority(WEATHER_CONTENT_AUTHORITY)
388            .path(WEATHER_CONTENT_PATH)
389            .appendPath(new Long(System.currentTimeMillis()).toString())
390            .build();
391
392        if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
393
394        Cursor cur;
395        try {
396            cur = managedQuery(
397                queryUri,
398                WEATHER_CONTENT_COLUMNS,
399                null,
400                null,
401                null);
402        } catch (RuntimeException e) {
403            Log.e(LOG_TAG, "Weather query failed", e);
404            cur = null;
405        }
406
407        if (cur != null && cur.moveToFirst()) {
408            if (DEBUG) {
409                java.lang.StringBuilder sb =
410                    new java.lang.StringBuilder("Weather query result: {");
411                for(int i=0; i<cur.getColumnCount(); i++) {
412                    if (i>0) sb.append(", ");
413                    sb.append(cur.getColumnName(i))
414                        .append("=")
415                        .append(cur.getString(i));
416                }
417                sb.append("}");
418                Log.d(LOG_TAG, sb.toString());
419            }
420
421            mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
422                cur.getColumnIndexOrThrow("iconResId")));
423            mWeatherCurrentTemperatureString = String.format("%d\u00b0",
424                (cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
425            mWeatherHighTemperatureString = String.format("%d\u00b0",
426                (cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
427            mWeatherLowTemperatureString = String.format("%d\u00b0",
428                (cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
429            mWeatherLocationString = cur.getString(
430                cur.getColumnIndexOrThrow("location"));
431        } else {
432            Log.w(LOG_TAG, "No weather information available (cur="
433                + cur +")");
434            mWeatherIconDrawable = null;
435            mWeatherHighTemperatureString = "";
436            mWeatherLowTemperatureString = "";
437            mWeatherLocationString = getString(R.string.weather_fetch_failure);
438        }
439
440        mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
441    }
442
443    private void refreshWeather() {
444        if (supportsWeather())
445            scheduleWeatherQueryDelayed(0);
446        updateWeatherDisplay(); // in case we have it cached
447    }
448
449    private void updateWeatherDisplay() {
450        if (mWeatherCurrentTemperature == null) return;
451
452        mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
453        mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
454        mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
455        mWeatherLocation.setText(mWeatherLocationString);
456        mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
457    }
458
459    // Adapted from KeyguardUpdateMonitor.java
460    private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
461        final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
462        if (pluggedIn != mPluggedIn) {
463            setWakeLock(pluggedIn);
464
465            if (pluggedIn) {
466                // policy: update weather info when attaching to power
467                requestWeatherDataFetch();
468            }
469        }
470        if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
471            mBatteryLevel = batteryLevel;
472            mPluggedIn = pluggedIn;
473            refreshBattery();
474        }
475    }
476
477    private void refreshBattery() {
478        if (mBatteryDisplay == null) return;
479
480        if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
481            mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
482                0, 0, android.R.drawable.ic_lock_idle_charging, 0);
483            mBatteryDisplay.setText(
484                getString(R.string.battery_charging_level, mBatteryLevel));
485            mBatteryDisplay.setVisibility(View.VISIBLE);
486        } else {
487            mBatteryDisplay.setVisibility(View.INVISIBLE);
488        }
489    }
490
491    private void refreshDate() {
492        final Date now = new Date();
493        if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
494        mDate.setText(DateFormat.format(mDateFormat, now));
495    }
496
497    private void refreshAlarm() {
498        if (mNextAlarm == null) return;
499
500        String nextAlarm = Settings.System.getString(getContentResolver(),
501                Settings.System.NEXT_ALARM_FORMATTED);
502        if (!TextUtils.isEmpty(nextAlarm)) {
503            mNextAlarm.setText(nextAlarm);
504            //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
505            //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
506            mNextAlarm.setVisibility(View.VISIBLE);
507        } else {
508            mNextAlarm.setVisibility(View.INVISIBLE);
509        }
510    }
511
512    private void refreshAll() {
513        refreshDate();
514        refreshAlarm();
515        refreshBattery();
516        refreshWeather();
517    }
518
519    private void doDim(boolean fade) {
520        View tintView = findViewById(R.id.window_tint);
521        if (tintView == null) return;
522
523        Window win = getWindow();
524        WindowManager.LayoutParams winParams = win.getAttributes();
525
526        winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
527        winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
528
529        // dim the wallpaper somewhat (how much is determined below)
530        winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
531
532        if (mDimmed) {
533            winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
534            winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED;
535            winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
536
537            // show the window tint
538            tintView.startAnimation(AnimationUtils.loadAnimation(this,
539                fade ? R.anim.dim
540                     : R.anim.dim_instant));
541        } else {
542            winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
543            winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL;
544            winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
545
546            // hide the window tint
547            tintView.startAnimation(AnimationUtils.loadAnimation(this,
548                fade ? R.anim.undim
549                     : R.anim.undim_instant));
550        }
551
552        win.setAttributes(winParams);
553    }
554
555    @Override
556    public void onNewIntent(Intent newIntent) {
557        super.onNewIntent(newIntent);
558        if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
559
560        // update our intent so that we can consult it to determine whether or
561        // not the most recent launch was via a dock event
562        setIntent(newIntent);
563    }
564
565    @Override
566    public void onResume() {
567        super.onResume();
568        if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent());
569
570        // reload the date format in case the user has changed settings
571        // recently
572        mDateFormat = getString(R.string.full_wday_month_day_no_year);
573
574        IntentFilter filter = new IntentFilter();
575        filter.addAction(Intent.ACTION_DATE_CHANGED);
576        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
577        filter.addAction(Intent.ACTION_DOCK_EVENT);
578        filter.addAction(ACTION_MIDNIGHT);
579        registerReceiver(mIntentReceiver, filter);
580
581        // Listen for updates to weather data
582        Uri weatherNotificationUri = new Uri.Builder()
583            .scheme(android.content.ContentResolver.SCHEME_CONTENT)
584            .authority(WEATHER_CONTENT_AUTHORITY)
585            .path(WEATHER_CONTENT_PATH)
586            .build();
587        getContentResolver().registerContentObserver(
588            weatherNotificationUri, true, mContentObserver);
589
590        // Elaborate mechanism to find out when the day rolls over
591        Calendar today = Calendar.getInstance();
592        today.set(Calendar.HOUR_OF_DAY, 0);
593        today.set(Calendar.MINUTE, 0);
594        today.set(Calendar.SECOND, 0);
595        today.add(Calendar.DATE, 1);
596        long alarmTimeUTC = today.getTimeInMillis() + today.get(Calendar.ZONE_OFFSET);
597        mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
598        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
599        am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent);
600        if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at "
601            + alarmTimeUTC + " repeating every "
602            + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent);
603
604        // If we weren't previously visible but now we are, it's because we're
605        // being started from another activity. So it's OK to un-dim.
606        if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) {
607            mDimmed = false;
608        }
609
610        // Adjust the display to reflect the currently chosen dim mode.
611        doDim(false);
612
613        restoreScreen(); // disable screen saver
614        refreshAll(); // will schedule periodic weather fetch
615
616        setWakeLock(mPluggedIn);
617
618        scheduleScreenSaver();
619
620        final boolean launchedFromDock
621            = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
622
623        if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) {
624            // policy: fetch weather if launched via dock connection
625            if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
626            requestWeatherDataFetch();
627        }
628
629        mLaunchedFromDock = launchedFromDock;
630    }
631
632    @Override
633    public void onPause() {
634        if (DEBUG) Log.d(LOG_TAG, "onPause");
635
636        // Turn off the screen saver and cancel any pending timeouts.
637        // (But don't un-dim.)
638        mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
639        restoreScreen();
640
641        // Other things we don't want to be doing in the background.
642        unregisterReceiver(mIntentReceiver);
643        getContentResolver().unregisterContentObserver(mContentObserver);
644
645        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
646        am.cancel(mMidnightIntent);
647        unscheduleWeatherQuery();
648
649        super.onPause();
650    }
651
652    private void initViews() {
653        // give up any internal focus before we switch layouts
654        final View focused = getCurrentFocus();
655        if (focused != null) focused.clearFocus();
656
657        setContentView(R.layout.desk_clock);
658
659        mTime = (DigitalClock) findViewById(R.id.time);
660        mDate = (TextView) findViewById(R.id.date);
661        mBatteryDisplay = (TextView) findViewById(R.id.battery);
662
663        mTime.getRootView().requestFocus();
664
665        mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
666        mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
667        mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
668        mWeatherLocation = (TextView) findViewById(R.id.weather_location);
669        mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
670
671        final View.OnClickListener alarmClickListener = new View.OnClickListener() {
672            public void onClick(View v) {
673                startActivity(new Intent(DeskClock.this, AlarmClock.class));
674            }
675        };
676
677        mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
678        mNextAlarm.setOnClickListener(alarmClickListener);
679
680        final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
681        alarmButton.setOnClickListener(alarmClickListener);
682
683        final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
684        galleryButton.setOnClickListener(new View.OnClickListener() {
685            public void onClick(View v) {
686                try {
687                    startActivity(new Intent(
688                        Intent.ACTION_VIEW,
689                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
690                            .putExtra("slideshow", true)
691                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
692                } catch (android.content.ActivityNotFoundException e) {
693                    Log.e(LOG_TAG, "Couldn't launch image browser", e);
694                }
695            }
696        });
697
698        final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
699        musicButton.setOnClickListener(new View.OnClickListener() {
700            public void onClick(View v) {
701                try {
702                    Intent musicAppQuery = getPackageManager()
703                        .getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
704                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
705                    if (musicAppQuery != null) {
706                        startActivity(musicAppQuery);
707                    }
708                } catch (android.content.ActivityNotFoundException e) {
709                    Log.e(LOG_TAG, "Couldn't launch music browser", e);
710                }
711            }
712        });
713
714        final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
715        homeButton.setOnClickListener(new View.OnClickListener() {
716            public void onClick(View v) {
717                startActivity(
718                    new Intent(Intent.ACTION_MAIN)
719                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)
720                        .addCategory(Intent.CATEGORY_HOME));
721            }
722        });
723
724        final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
725        nightmodeButton.setOnClickListener(new View.OnClickListener() {
726            public void onClick(View v) {
727                mDimmed = ! mDimmed;
728                doDim(true);
729            }
730        });
731
732        nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
733            public boolean onLongClick(View v) {
734                saveScreen();
735                return true;
736            }
737        });
738
739        final View weatherView = findViewById(R.id.weather);
740        weatherView.setOnClickListener(new View.OnClickListener() {
741            public void onClick(View v) {
742                if (!supportsWeather()) return;
743
744                Intent genieAppQuery = getPackageManager()
745                    .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
746                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
747                if (genieAppQuery != null) {
748                    startActivity(genieAppQuery);
749                }
750            }
751        });
752
753        final View tintView = findViewById(R.id.window_tint);
754        tintView.setOnTouchListener(new View.OnTouchListener() {
755            public boolean onTouch(View v, MotionEvent event) {
756                if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) {
757                    // We want to un-dim the whole screen on tap.
758                    // ...Unless the user is specifically tapping on the dim
759                    // widget, in which case let it do the work.
760                    Rect r = new Rect();
761                    nightmodeButton.getHitRect(r);
762                    int[] gloc = new int[2];
763                    nightmodeButton.getLocationInWindow(gloc);
764                    r.offsetTo(gloc[0], gloc[1]); // convert to window coords
765
766                    if (!r.contains((int) event.getX(), (int) event.getY())) {
767                        mDimmed = false;
768                        doDim(true);
769                    }
770                }
771                return false; // always pass the click through
772            }
773        });
774
775        // Tidy up awkward focus behavior: the first view to be focused in
776        // trackball mode should be the alarms button
777        final ViewTreeObserver vto = alarmButton.getViewTreeObserver();
778        vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
779            public void onGlobalFocusChanged(View oldFocus, View newFocus) {
780                if (oldFocus == null && newFocus == nightmodeButton) {
781                    alarmButton.requestFocus();
782                }
783            }
784        });
785    }
786
787    @Override
788    public void onConfigurationChanged(Configuration newConfig) {
789        super.onConfigurationChanged(newConfig);
790        if (mScreenSaverMode) {
791            moveScreenSaver();
792        } else {
793            initViews();
794            doDim(false);
795            refreshAll();
796        }
797    }
798
799    @Override
800    public boolean onOptionsItemSelected(MenuItem item) {
801        switch (item.getItemId()) {
802            case R.id.menu_item_alarms:
803                startActivity(new Intent(DeskClock.this, AlarmClock.class));
804                return true;
805            case R.id.menu_item_add_alarm:
806                startActivity(new Intent(this, SetAlarm.class));
807                return true;
808            case R.id.menu_item_dock_settings:
809                startActivity(new Intent(DOCK_SETTINGS_ACTION));
810                return true;
811            default:
812                return false;
813        }
814    }
815
816    @Override
817    public boolean onCreateOptionsMenu(Menu menu) {
818        MenuInflater inflater = getMenuInflater();
819        inflater.inflate(R.menu.desk_clock_menu, menu);
820        return true;
821    }
822
823    @Override
824    protected void onCreate(Bundle icicle) {
825        super.onCreate(icicle);
826
827        mRNG = new Random();
828
829        try {
830            mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
831        } catch (PackageManager.NameNotFoundException e) {
832            // no weather info available
833            Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
834        }
835
836        initViews();
837    }
838
839}
840