DeskClock.java revision abc34112bd18bc0fc068ffa30ca07ae161bc9f0a
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                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
269                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
270                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
271        if (hold)
272            winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
273        else
274            winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
275        win.setAttributes(winParams);
276    }
277
278    private void scheduleScreenSaver() {
279        // reschedule screen saver
280        mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
281        mHandy.sendMessageDelayed(
282            Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG),
283            SCREEN_SAVER_TIMEOUT);
284    }
285
286    private void restoreScreen() {
287        if (!mScreenSaverMode) return;
288        if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
289        mScreenSaverMode = false;
290        initViews();
291        doDim(false); // restores previous dim mode
292        // policy: update weather info when returning from screen saver
293        if (mPluggedIn) requestWeatherDataFetch();
294
295        scheduleScreenSaver();
296
297        refreshAll();
298    }
299
300    // Special screen-saver mode for OLED displays that burn in quickly
301    private void saveScreen() {
302        if (mScreenSaverMode) return;
303        if (DEBUG) Log.d(LOG_TAG, "saveScreen");
304
305        // quickly stash away the x/y of the current date
306        final View oldTimeDate = findViewById(R.id.time_date);
307        int oldLoc[] = new int[2];
308        oldTimeDate.getLocationOnScreen(oldLoc);
309
310        mScreenSaverMode = true;
311        Window win = getWindow();
312        WindowManager.LayoutParams winParams = win.getAttributes();
313        winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
314        win.setAttributes(winParams);
315
316        // give up any internal focus before we switch layouts
317        final View focused = getCurrentFocus();
318        if (focused != null) focused.clearFocus();
319
320        setContentView(R.layout.desk_clock_saver);
321
322        mTime = (DigitalClock) findViewById(R.id.time);
323        mDate = (TextView) findViewById(R.id.date);
324        mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
325
326        final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
327
328        ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
329        ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
330        mDate.setTextColor(color);
331        mNextAlarm.setTextColor(color);
332        mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
333            getResources().getDrawable(mDimmed
334                ? R.drawable.ic_lock_idle_alarm_saver_dim
335                : R.drawable.ic_lock_idle_alarm_saver),
336            null, null, null);
337
338        mBatteryDisplay =
339        mWeatherCurrentTemperature =
340        mWeatherHighTemperature =
341        mWeatherLowTemperature =
342        mWeatherLocation = null;
343        mWeatherIcon = null;
344
345        refreshDate();
346        refreshAlarm();
347
348        moveScreenSaverTo(oldLoc[0], oldLoc[1]);
349    }
350
351    @Override
352    public void onUserInteraction() {
353        if (mScreenSaverMode)
354            restoreScreen();
355    }
356
357    // Tell the Genie widget to load new data from the network.
358    private void requestWeatherDataFetch() {
359        if (DEBUG) Log.d(LOG_TAG, "forcing the Genie widget to update weather now...");
360        sendBroadcast(new Intent(ACTION_GENIE_REFRESH).putExtra("requestWeather", true));
361        // we expect the result to show up in our content observer
362    }
363
364    private boolean supportsWeather() {
365        return (mGenieResources != null);
366    }
367
368    private void scheduleWeatherQueryDelayed(long delay) {
369        // cancel any existing scheduled queries
370        unscheduleWeatherQuery();
371
372        if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
373
374        mHandy.sendEmptyMessageDelayed(QUERY_WEATHER_DATA_MSG, delay);
375    }
376
377    private void unscheduleWeatherQuery() {
378        mHandy.removeMessages(QUERY_WEATHER_DATA_MSG);
379    }
380
381    private void queryWeatherData() {
382        // if we couldn't load the weather widget's resources, we simply
383        // assume it's not present on the device.
384        if (mGenieResources == null) return;
385
386        Uri queryUri = new Uri.Builder()
387            .scheme(android.content.ContentResolver.SCHEME_CONTENT)
388            .authority(WEATHER_CONTENT_AUTHORITY)
389            .path(WEATHER_CONTENT_PATH)
390            .appendPath(new Long(System.currentTimeMillis()).toString())
391            .build();
392
393        if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
394
395        Cursor cur;
396        try {
397            cur = managedQuery(
398                queryUri,
399                WEATHER_CONTENT_COLUMNS,
400                null,
401                null,
402                null);
403        } catch (RuntimeException e) {
404            Log.e(LOG_TAG, "Weather query failed", e);
405            cur = null;
406        }
407
408        if (cur != null && cur.moveToFirst()) {
409            if (DEBUG) {
410                java.lang.StringBuilder sb =
411                    new java.lang.StringBuilder("Weather query result: {");
412                for(int i=0; i<cur.getColumnCount(); i++) {
413                    if (i>0) sb.append(", ");
414                    sb.append(cur.getColumnName(i))
415                        .append("=")
416                        .append(cur.getString(i));
417                }
418                sb.append("}");
419                Log.d(LOG_TAG, sb.toString());
420            }
421
422            mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
423                cur.getColumnIndexOrThrow("iconResId")));
424            mWeatherCurrentTemperatureString = String.format("%d\u00b0",
425                (cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
426            mWeatherHighTemperatureString = String.format("%d\u00b0",
427                (cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
428            mWeatherLowTemperatureString = String.format("%d\u00b0",
429                (cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
430            mWeatherLocationString = cur.getString(
431                cur.getColumnIndexOrThrow("location"));
432        } else {
433            Log.w(LOG_TAG, "No weather information available (cur="
434                + cur +")");
435            mWeatherIconDrawable = null;
436            mWeatherHighTemperatureString = "";
437            mWeatherLowTemperatureString = "";
438            mWeatherLocationString = getString(R.string.weather_fetch_failure);
439        }
440
441        mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
442    }
443
444    private void refreshWeather() {
445        if (supportsWeather())
446            scheduleWeatherQueryDelayed(0);
447        updateWeatherDisplay(); // in case we have it cached
448    }
449
450    private void updateWeatherDisplay() {
451        if (mWeatherCurrentTemperature == null) return;
452
453        mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
454        mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
455        mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
456        mWeatherLocation.setText(mWeatherLocationString);
457        mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
458    }
459
460    // Adapted from KeyguardUpdateMonitor.java
461    private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
462        final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
463        if (pluggedIn != mPluggedIn) {
464            setWakeLock(pluggedIn);
465
466            if (pluggedIn) {
467                // policy: update weather info when attaching to power
468                requestWeatherDataFetch();
469            }
470        }
471        if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
472            mBatteryLevel = batteryLevel;
473            mPluggedIn = pluggedIn;
474            refreshBattery();
475        }
476    }
477
478    private void refreshBattery() {
479        if (mBatteryDisplay == null) return;
480
481        if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
482            mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
483                0, 0, android.R.drawable.ic_lock_idle_charging, 0);
484            mBatteryDisplay.setText(
485                getString(R.string.battery_charging_level, mBatteryLevel));
486            mBatteryDisplay.setVisibility(View.VISIBLE);
487        } else {
488            mBatteryDisplay.setVisibility(View.INVISIBLE);
489        }
490    }
491
492    private void refreshDate() {
493        final Date now = new Date();
494        if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
495        mDate.setText(DateFormat.format(mDateFormat, now));
496    }
497
498    private void refreshAlarm() {
499        if (mNextAlarm == null) return;
500
501        String nextAlarm = Settings.System.getString(getContentResolver(),
502                Settings.System.NEXT_ALARM_FORMATTED);
503        if (!TextUtils.isEmpty(nextAlarm)) {
504            mNextAlarm.setText(nextAlarm);
505            //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
506            //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
507            mNextAlarm.setVisibility(View.VISIBLE);
508        } else {
509            mNextAlarm.setVisibility(View.INVISIBLE);
510        }
511    }
512
513    private void refreshAll() {
514        refreshDate();
515        refreshAlarm();
516        refreshBattery();
517        refreshWeather();
518    }
519
520    private void doDim(boolean fade) {
521        View tintView = findViewById(R.id.window_tint);
522        if (tintView == null) return;
523
524        Window win = getWindow();
525        WindowManager.LayoutParams winParams = win.getAttributes();
526
527        winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
528        winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
529
530        // dim the wallpaper somewhat (how much is determined below)
531        winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
532
533        if (mDimmed) {
534            winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
535            winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED;
536            winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
537
538            // show the window tint
539            tintView.startAnimation(AnimationUtils.loadAnimation(this,
540                fade ? R.anim.dim
541                     : R.anim.dim_instant));
542        } else {
543            winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
544            winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL;
545            winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
546
547            // hide the window tint
548            tintView.startAnimation(AnimationUtils.loadAnimation(this,
549                fade ? R.anim.undim
550                     : R.anim.undim_instant));
551        }
552
553        win.setAttributes(winParams);
554    }
555
556    @Override
557    public void onNewIntent(Intent newIntent) {
558        super.onNewIntent(newIntent);
559        if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
560
561        // update our intent so that we can consult it to determine whether or
562        // not the most recent launch was via a dock event
563        setIntent(newIntent);
564    }
565
566    @Override
567    public void onResume() {
568        super.onResume();
569        if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent());
570
571        // reload the date format in case the user has changed settings
572        // recently
573        mDateFormat = getString(R.string.full_wday_month_day_no_year);
574
575        IntentFilter filter = new IntentFilter();
576        filter.addAction(Intent.ACTION_DATE_CHANGED);
577        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
578        filter.addAction(Intent.ACTION_DOCK_EVENT);
579        filter.addAction(ACTION_MIDNIGHT);
580        registerReceiver(mIntentReceiver, filter);
581
582        // Listen for updates to weather data
583        Uri weatherNotificationUri = new Uri.Builder()
584            .scheme(android.content.ContentResolver.SCHEME_CONTENT)
585            .authority(WEATHER_CONTENT_AUTHORITY)
586            .path(WEATHER_CONTENT_PATH)
587            .build();
588        getContentResolver().registerContentObserver(
589            weatherNotificationUri, true, mContentObserver);
590
591        // Elaborate mechanism to find out when the day rolls over
592        Calendar today = Calendar.getInstance();
593        today.set(Calendar.HOUR_OF_DAY, 0);
594        today.set(Calendar.MINUTE, 0);
595        today.set(Calendar.SECOND, 0);
596        today.add(Calendar.DATE, 1);
597        long alarmTimeUTC = today.getTimeInMillis() + today.get(Calendar.ZONE_OFFSET);
598        mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
599        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
600        am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent);
601        if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at "
602            + alarmTimeUTC + " repeating every "
603            + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent);
604
605        // If we weren't previously visible but now we are, it's because we're
606        // being started from another activity. So it's OK to un-dim.
607        if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) {
608            mDimmed = false;
609        }
610
611        // Adjust the display to reflect the currently chosen dim mode.
612        doDim(false);
613
614        restoreScreen(); // disable screen saver
615        refreshAll(); // will schedule periodic weather fetch
616
617        setWakeLock(mPluggedIn);
618
619        scheduleScreenSaver();
620
621        final boolean launchedFromDock
622            = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
623
624        if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) {
625            // policy: fetch weather if launched via dock connection
626            if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
627            requestWeatherDataFetch();
628        }
629
630        mLaunchedFromDock = launchedFromDock;
631    }
632
633    @Override
634    public void onPause() {
635        if (DEBUG) Log.d(LOG_TAG, "onPause");
636
637        // Turn off the screen saver and cancel any pending timeouts.
638        // (But don't un-dim.)
639        mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
640        restoreScreen();
641
642        // Other things we don't want to be doing in the background.
643        unregisterReceiver(mIntentReceiver);
644        getContentResolver().unregisterContentObserver(mContentObserver);
645
646        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
647        am.cancel(mMidnightIntent);
648        unscheduleWeatherQuery();
649
650        super.onPause();
651    }
652
653    private void initViews() {
654        // give up any internal focus before we switch layouts
655        final View focused = getCurrentFocus();
656        if (focused != null) focused.clearFocus();
657
658        setContentView(R.layout.desk_clock);
659
660        mTime = (DigitalClock) findViewById(R.id.time);
661        mDate = (TextView) findViewById(R.id.date);
662        mBatteryDisplay = (TextView) findViewById(R.id.battery);
663
664        mTime.getRootView().requestFocus();
665
666        mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
667        mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
668        mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
669        mWeatherLocation = (TextView) findViewById(R.id.weather_location);
670        mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
671
672        final View.OnClickListener alarmClickListener = new View.OnClickListener() {
673            public void onClick(View v) {
674                startActivity(new Intent(DeskClock.this, AlarmClock.class));
675            }
676        };
677
678        mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
679        mNextAlarm.setOnClickListener(alarmClickListener);
680
681        final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
682        alarmButton.setOnClickListener(alarmClickListener);
683
684        final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
685        galleryButton.setOnClickListener(new View.OnClickListener() {
686            public void onClick(View v) {
687                try {
688                    startActivity(new Intent(
689                        Intent.ACTION_VIEW,
690                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
691                            .putExtra("slideshow", true)
692                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
693                } catch (android.content.ActivityNotFoundException e) {
694                    Log.e(LOG_TAG, "Couldn't launch image browser", e);
695                }
696            }
697        });
698
699        final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
700        musicButton.setOnClickListener(new View.OnClickListener() {
701            public void onClick(View v) {
702                try {
703                    Intent musicAppQuery = getPackageManager()
704                        .getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
705                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
706                    if (musicAppQuery != null) {
707                        startActivity(musicAppQuery);
708                    }
709                } catch (android.content.ActivityNotFoundException e) {
710                    Log.e(LOG_TAG, "Couldn't launch music browser", e);
711                }
712            }
713        });
714
715        final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
716        homeButton.setOnClickListener(new View.OnClickListener() {
717            public void onClick(View v) {
718                startActivity(
719                    new Intent(Intent.ACTION_MAIN)
720                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)
721                        .addCategory(Intent.CATEGORY_HOME));
722            }
723        });
724
725        final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
726        nightmodeButton.setOnClickListener(new View.OnClickListener() {
727            public void onClick(View v) {
728                mDimmed = ! mDimmed;
729                doDim(true);
730            }
731        });
732
733        nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
734            public boolean onLongClick(View v) {
735                saveScreen();
736                return true;
737            }
738        });
739
740        final View weatherView = findViewById(R.id.weather);
741        weatherView.setOnClickListener(new View.OnClickListener() {
742            public void onClick(View v) {
743                if (!supportsWeather()) return;
744
745                Intent genieAppQuery = getPackageManager()
746                    .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
747                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
748                if (genieAppQuery != null) {
749                    startActivity(genieAppQuery);
750                }
751            }
752        });
753
754        final View tintView = findViewById(R.id.window_tint);
755        tintView.setOnTouchListener(new View.OnTouchListener() {
756            public boolean onTouch(View v, MotionEvent event) {
757                if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) {
758                    // We want to un-dim the whole screen on tap.
759                    // ...Unless the user is specifically tapping on the dim
760                    // widget, in which case let it do the work.
761                    Rect r = new Rect();
762                    nightmodeButton.getHitRect(r);
763                    int[] gloc = new int[2];
764                    nightmodeButton.getLocationInWindow(gloc);
765                    r.offsetTo(gloc[0], gloc[1]); // convert to window coords
766
767                    if (!r.contains((int) event.getX(), (int) event.getY())) {
768                        mDimmed = false;
769                        doDim(true);
770                    }
771                }
772                return false; // always pass the click through
773            }
774        });
775
776        // Tidy up awkward focus behavior: the first view to be focused in
777        // trackball mode should be the alarms button
778        final ViewTreeObserver vto = alarmButton.getViewTreeObserver();
779        vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
780            public void onGlobalFocusChanged(View oldFocus, View newFocus) {
781                if (oldFocus == null && newFocus == nightmodeButton) {
782                    alarmButton.requestFocus();
783                }
784            }
785        });
786    }
787
788    @Override
789    public void onConfigurationChanged(Configuration newConfig) {
790        super.onConfigurationChanged(newConfig);
791        if (mScreenSaverMode) {
792            moveScreenSaver();
793        } else {
794            initViews();
795            doDim(false);
796            refreshAll();
797        }
798    }
799
800    @Override
801    public boolean onOptionsItemSelected(MenuItem item) {
802        switch (item.getItemId()) {
803            case R.id.menu_item_alarms:
804                startActivity(new Intent(DeskClock.this, AlarmClock.class));
805                return true;
806            case R.id.menu_item_add_alarm:
807                startActivity(new Intent(this, SetAlarm.class));
808                return true;
809            case R.id.menu_item_dock_settings:
810                startActivity(new Intent(DOCK_SETTINGS_ACTION));
811                return true;
812            default:
813                return false;
814        }
815    }
816
817    @Override
818    public boolean onCreateOptionsMenu(Menu menu) {
819        MenuInflater inflater = getMenuInflater();
820        inflater.inflate(R.menu.desk_clock_menu, menu);
821        return true;
822    }
823
824    @Override
825    protected void onCreate(Bundle icicle) {
826        super.onCreate(icicle);
827
828        mRNG = new Random();
829
830        try {
831            mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
832        } catch (PackageManager.NameNotFoundException e) {
833            // no weather info available
834            Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
835        }
836
837        initViews();
838    }
839
840}
841