OSDN Git Service

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