OSDN Git Service

Use an alarm to refresh the date 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.util.DisplayMetrics;
45 import android.util.Log;
46 import android.view.ContextMenu.ContextMenuInfo;
47 import android.view.ContextMenu;
48 import android.view.LayoutInflater;
49 import android.view.Menu;
50 import android.view.MenuInflater;
51 import android.view.MenuItem;
52 import android.view.View.OnClickListener;
53 import android.view.View.OnCreateContextMenuListener;
54 import android.view.View;
55 import android.view.ViewGroup;
56 import android.view.Window;
57 import android.view.WindowManager;
58 import android.view.animation.Animation;
59 import android.view.animation.AnimationUtils;
60 import android.view.animation.TranslateAnimation;
61 import android.widget.AbsoluteLayout;
62 import android.widget.AdapterView.AdapterContextMenuInfo;
63 import android.widget.AdapterView.OnItemClickListener;
64 import android.widget.AdapterView;
65 import android.widget.Button;
66 import android.widget.CheckBox;
67 import android.widget.ImageButton;
68 import android.widget.ImageView;
69 import android.widget.TextView;
70
71 import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
72 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
73 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
74
75 import java.io.IOException;
76 import java.io.InputStream;
77 import java.text.DateFormat;
78 import java.text.SimpleDateFormat;
79 import java.util.Calendar;
80 import java.util.Date;
81 import java.util.Locale;
82 import java.util.Random;
83
84 /**
85  * DeskClock clock view for desk docks.
86  */
87 public class DeskClock extends Activity {
88     private static final boolean DEBUG = false;
89
90     private static final String LOG_TAG = "DeskClock";
91
92     // Intent used to start the music player.
93     private static final String MUSIC_NOW_PLAYING = "com.android.music.PLAYBACK_VIEWER";
94
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 FETCH_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 = 10 * 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     // Internal message IDs.
113     private final int FETCH_WEATHER_DATA_MSG     = 0x1000;
114     private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
115     private final int SCREEN_SAVER_TIMEOUT_MSG   = 0x2000;
116     private final int SCREEN_SAVER_MOVE_MSG      = 0x2001;
117
118     // Weather widget query information.
119     private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
120     private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
121     private static final String WEATHER_CONTENT_PATH = "/weather/current";
122     private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
123             "location",
124             "timestamp",
125             "temperature",
126             "highTemperature",
127             "lowTemperature",
128             "iconUrl",
129             "iconResId",
130             "description",
131         };
132
133     // State variables follow.
134     private DigitalClock mTime;
135     private TextView mDate;
136
137     private TextView mNextAlarm = null;
138     private TextView mBatteryDisplay;
139
140     private TextView mWeatherCurrentTemperature;
141     private TextView mWeatherHighTemperature;
142     private TextView mWeatherLowTemperature;
143     private TextView mWeatherLocation;
144     private ImageView mWeatherIcon;
145
146     private String mWeatherCurrentTemperatureString;
147     private String mWeatherHighTemperatureString;
148     private String mWeatherLowTemperatureString;
149     private String mWeatherLocationString;
150     private Drawable mWeatherIconDrawable;
151
152     private Resources mGenieResources = null;
153
154     private boolean mDimmed = false;
155     private boolean mScreenSaverMode = false;
156
157     private DateFormat mDateFormat;
158
159     private int mBatteryLevel = -1;
160     private boolean mPluggedIn = false;
161
162     private boolean mInDock = false;
163
164     private int mIdleTimeoutEpoch = 0;
165
166     private boolean mWeatherFetchScheduled = false;
167
168     private Random mRNG;
169
170     private PendingIntent mMidnightIntent;
171
172     private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
173         @Override
174         public void onReceive(Context context, Intent intent) {
175             final String action = intent.getAction();
176             if (Intent.ACTION_DATE_CHANGED.equals(action)) {
177                 refreshDate();
178             } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
179                 handleBatteryUpdate(
180                     intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
181                     intent.getIntExtra("level", 0));
182             }
183         }
184     };
185
186     private final Handler mHandy = new Handler() {
187         @Override
188         public void handleMessage(Message m) {
189             if (m.what == FETCH_WEATHER_DATA_MSG) {
190                 if (!mWeatherFetchScheduled) return;
191                 mWeatherFetchScheduled = false;
192                 new Thread() { public void run() { fetchWeatherData(); } }.start();
193                 scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
194             } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
195                 updateWeatherDisplay();
196             } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
197                 if (m.arg1 == mIdleTimeoutEpoch) {
198                     saveScreen();
199                 }
200             } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
201                 moveScreenSaver();
202             }
203         }
204     };
205
206
207     private void moveScreenSaver() {
208         moveScreenSaverTo(-1,-1);
209     }
210     private void moveScreenSaverTo(int x, int y) {
211         if (!mScreenSaverMode) return;
212
213         final View time_date = findViewById(R.id.time_date);
214
215         DisplayMetrics metrics = new DisplayMetrics();
216         getWindowManager().getDefaultDisplay().getMetrics(metrics);
217
218         if (x < 0 || y < 0) {
219             int myWidth = time_date.getMeasuredWidth();
220             int myHeight = time_date.getMeasuredHeight();
221             x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
222             y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
223         }
224
225         if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
226                 System.currentTimeMillis(), x, y));
227
228         time_date.setLayoutParams(new AbsoluteLayout.LayoutParams(
229             ViewGroup.LayoutParams.WRAP_CONTENT,
230             ViewGroup.LayoutParams.WRAP_CONTENT,
231             x,
232             y));
233
234         // Synchronize our jumping so that it happens exactly on the second.
235         mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
236             SCREEN_SAVER_MOVE_DELAY +
237             (1000 - (System.currentTimeMillis() % 1000)));
238     }
239
240     private void setWakeLock(boolean hold) {
241         if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
242         Window win = getWindow();
243         WindowManager.LayoutParams winParams = win.getAttributes();
244         winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
245         winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
246         winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
247         if (hold)
248             winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
249         else
250             winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
251         win.setAttributes(winParams);
252     }
253
254     private void restoreScreen() {
255         if (!mScreenSaverMode) return;
256         if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
257         mScreenSaverMode = false;
258         initViews();
259         doDim(false); // restores previous dim mode
260         refreshAll();
261     }
262
263     // Special screen-saver mode for OLED displays that burn in quickly
264     private void saveScreen() {
265         if (mScreenSaverMode) return;
266         if (DEBUG) Log.d(LOG_TAG, "saveScreen");
267
268         // quickly stash away the x/y of the current date
269         final View oldTimeDate = findViewById(R.id.time_date);
270         int oldLoc[] = new int[2];
271         oldTimeDate.getLocationOnScreen(oldLoc);
272
273         mScreenSaverMode = true;
274         Window win = getWindow();
275         WindowManager.LayoutParams winParams = win.getAttributes();
276         winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
277         win.setAttributes(winParams);
278
279         // give up any internal focus before we switch layouts
280         final View focused = getCurrentFocus();
281         if (focused != null) focused.clearFocus();
282
283         setContentView(R.layout.desk_clock_saver);
284
285         mTime = (DigitalClock) findViewById(R.id.time);
286         mDate = (TextView) findViewById(R.id.date);
287
288         final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
289
290         ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
291         ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
292         mDate.setTextColor(color);
293
294         mBatteryDisplay =
295         mNextAlarm =
296         mWeatherCurrentTemperature =
297         mWeatherHighTemperature =
298         mWeatherLowTemperature =
299         mWeatherLocation = null;
300         mWeatherIcon = null;
301
302         refreshDate();
303
304         moveScreenSaverTo(oldLoc[0], oldLoc[1]);
305     }
306
307     @Override
308     public void onUserInteraction() {
309         if (mScreenSaverMode)
310             restoreScreen();
311     }
312
313     private boolean supportsWeather() {
314         return (mGenieResources != null);
315     }
316
317     private void scheduleWeatherFetchDelayed(long delay) {
318         if (mWeatherFetchScheduled) return;
319
320         if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
321
322         mWeatherFetchScheduled = true;
323
324         mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
325     }
326
327     private void unscheduleWeatherFetch() {
328         mWeatherFetchScheduled = false;
329     }
330
331     private static final boolean sCelsius;
332     static {
333         String cc = Locale.getDefault().getCountry().toLowerCase();
334         sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
335     }
336
337     private static int celsiusToLocal(int tempC) {
338         return sCelsius ? tempC : (int) Math.round(tempC * 1.8f + 32);
339     }
340
341     private void fetchWeatherData() {
342         // if we couldn't load the weather widget's resources, we simply
343         // assume it's not present on the device.
344         if (mGenieResources == null) return;
345
346         Uri queryUri = new Uri.Builder()
347             .scheme(android.content.ContentResolver.SCHEME_CONTENT)
348             .authority(WEATHER_CONTENT_AUTHORITY)
349             .path(WEATHER_CONTENT_PATH)
350             .appendPath(new Long(System.currentTimeMillis()).toString())
351             .build();
352
353         if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
354
355         Cursor cur;
356         try {
357             cur = managedQuery(
358                 queryUri,
359                 WEATHER_CONTENT_COLUMNS,
360                 null,
361                 null,
362                 null);
363         } catch (RuntimeException e) {
364             Log.e(LOG_TAG, "Weather query failed", e);
365             cur = null;
366         }
367
368         if (cur != null && cur.moveToFirst()) {
369             if (DEBUG) {
370                 java.lang.StringBuilder sb =
371                     new java.lang.StringBuilder("Weather query result: {");
372                 for(int i=0; i<cur.getColumnCount(); i++) {
373                     if (i>0) sb.append(", ");
374                     sb.append(cur.getColumnName(i))
375                         .append("=")
376                         .append(cur.getString(i));
377                 }
378                 sb.append("}");
379                 Log.d(LOG_TAG, sb.toString());
380             }
381
382             mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
383                 cur.getColumnIndexOrThrow("iconResId")));
384             mWeatherCurrentTemperatureString = String.format("%d\u00b0",
385                 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
386             mWeatherHighTemperatureString = String.format("%d\u00b0",
387                 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
388             mWeatherLowTemperatureString = String.format("%d\u00b0",
389                 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
390             mWeatherLocationString = cur.getString(
391                 cur.getColumnIndexOrThrow("location"));
392         } else {
393             Log.w(LOG_TAG, "No weather information available (cur="
394                 + cur +")");
395             mWeatherIconDrawable = null;
396             mWeatherHighTemperatureString = "";
397             mWeatherLowTemperatureString = "";
398             mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
399         }
400
401         mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
402     }
403
404     private void refreshWeather() {
405         if (supportsWeather())
406             scheduleWeatherFetchDelayed(0);
407         updateWeatherDisplay(); // in case we have it cached
408     }
409
410     private void updateWeatherDisplay() {
411         if (mWeatherCurrentTemperature == null) return;
412
413         mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
414         mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
415         mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
416         mWeatherLocation.setText(mWeatherLocationString);
417         mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
418     }
419
420     // Adapted from KeyguardUpdateMonitor.java
421     private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
422         final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
423         if (pluggedIn != mPluggedIn) {
424             setWakeLock(pluggedIn);
425         }
426         if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
427             mBatteryLevel = batteryLevel;
428             mPluggedIn = pluggedIn;
429             refreshBattery();
430         }
431     }
432
433     private void refreshBattery() {
434         if (mBatteryDisplay == null) return;
435
436         if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
437             mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
438                 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
439             mBatteryDisplay.setText(
440                 getString(R.string.battery_charging_level, mBatteryLevel));
441             mBatteryDisplay.setVisibility(View.VISIBLE);
442         } else {
443             mBatteryDisplay.setVisibility(View.INVISIBLE);
444         }
445     }
446
447     private void refreshDate() {
448         final Date now = new Date();
449         if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
450         mDate.setText(mDateFormat.format(now));
451     }
452
453     private void refreshAlarm() {
454         if (mNextAlarm == null) return;
455
456         String nextAlarm = Settings.System.getString(getContentResolver(),
457                 Settings.System.NEXT_ALARM_FORMATTED);
458         if (!TextUtils.isEmpty(nextAlarm)) {
459             mNextAlarm.setText(nextAlarm);
460             //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
461             //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
462             mNextAlarm.setVisibility(View.VISIBLE);
463         } else {
464             mNextAlarm.setVisibility(View.INVISIBLE);
465         }
466     }
467
468     private void refreshAll() {
469         refreshDate();
470         refreshAlarm();
471         refreshBattery();
472         refreshWeather();
473     }
474
475     private void doDim(boolean fade) {
476         View tintView = findViewById(R.id.window_tint);
477         if (tintView == null) return;
478
479         Window win = getWindow();
480         WindowManager.LayoutParams winParams = win.getAttributes();
481
482         winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
483         winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
484
485         // dim the wallpaper somewhat (how much is determined below)
486         winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
487
488         if (mDimmed) {
489             winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
490             winParams.dimAmount = 0.67f; // pump up contrast in dim mode
491
492             // show the window tint
493             tintView.startAnimation(AnimationUtils.loadAnimation(this,
494                 fade ? R.anim.dim
495                      : R.anim.dim_instant));
496         } else {
497             winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
498             winParams.dimAmount = 0.5f; // lower contrast in normal mode
499
500             // hide the window tint
501             tintView.startAnimation(AnimationUtils.loadAnimation(this,
502                 fade ? R.anim.undim
503                      : R.anim.undim_instant));
504         }
505
506         win.setAttributes(winParams);
507     }
508
509     @Override
510     public void onResume() {
511         super.onResume();
512         if (DEBUG) Log.d(LOG_TAG, "onResume");
513
514         // reload the date format in case the user has changed settings
515         // recently
516         final SimpleDateFormat dateFormat = (SimpleDateFormat)
517                 java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
518         // This is a little clumsy; we want to honor the locale's date format
519         // (rather than simply hardcoding "Weekday, Month Date") but
520         // DateFormat.FULL includes the year (at least, in enUS). So we lop
521         // that bit off if it's there; should have no effect on
522         // locale-specific date strings that look different.
523         mDateFormat = new SimpleDateFormat(dateFormat.toPattern()
524                     .replace(", yyyy", "")); // no year
525
526         IntentFilter filter = new IntentFilter();
527         filter.addAction(Intent.ACTION_DATE_CHANGED);
528         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
529         filter.addAction(ACTION_MIDNIGHT);
530
531         Calendar today = Calendar.getInstance();
532         today.add(Calendar.DATE, 1);
533         mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
534         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
535         am.setRepeating(AlarmManager.RTC, today.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mMidnightIntent);
536         registerReceiver(mIntentReceiver, filter);
537
538         doDim(false);
539         restoreScreen();
540         refreshAll(); // will schedule periodic weather fetch
541
542         setWakeLock(mPluggedIn);
543
544         mIdleTimeoutEpoch++;
545         mHandy.sendMessageDelayed(
546             Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
547             SCREEN_SAVER_TIMEOUT);
548
549         final boolean launchedFromDock 
550             = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
551
552         if (supportsWeather() && launchedFromDock && !mInDock) {
553             if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
554             sendBroadcast(
555                 new Intent("com.google.android.apps.genie.REFRESH")
556                     .putExtra("requestWeather", true));
557         }
558
559         mInDock = launchedFromDock;
560     }
561
562     @Override
563     public void onPause() {
564         if (DEBUG) Log.d(LOG_TAG, "onPause");
565
566         // Turn off the screen saver. (But don't un-dim.)
567         restoreScreen();
568
569         // Other things we don't want to be doing in the background.
570         unregisterReceiver(mIntentReceiver);
571         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
572         am.cancel(mMidnightIntent);
573         unscheduleWeatherFetch();
574
575         super.onPause();
576     }
577
578     @Override
579     public void onStop() {
580         if (DEBUG) Log.d(LOG_TAG, "onStop");
581
582         // Avoid situations where the user launches Alarm Clock and is
583         // surprised to find it in dim mode (because it was last used in dim
584         // mode, but that last use is long in the past).
585         mDimmed = false;
586
587         super.onStop();
588     }
589
590     private void initViews() {
591         // give up any internal focus before we switch layouts
592         final View focused = getCurrentFocus();
593         if (focused != null) focused.clearFocus();
594
595         setContentView(R.layout.desk_clock);
596
597         mTime = (DigitalClock) findViewById(R.id.time);
598         mDate = (TextView) findViewById(R.id.date);
599         mBatteryDisplay = (TextView) findViewById(R.id.battery);
600
601         mTime.getRootView().requestFocus();
602
603         mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
604         mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
605         mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
606         mWeatherLocation = (TextView) findViewById(R.id.weather_location);
607         mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
608
609         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
610
611         final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
612         alarmButton.setOnClickListener(new View.OnClickListener() {
613             public void onClick(View v) {
614                 startActivity(new Intent(DeskClock.this, AlarmClock.class));
615             }
616         });
617
618         final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
619         galleryButton.setOnClickListener(new View.OnClickListener() {
620             public void onClick(View v) {
621                 try {
622                     startActivity(new Intent(
623                         Intent.ACTION_VIEW,
624                         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
625                             .putExtra("slideshow", true));
626                 } catch (android.content.ActivityNotFoundException e) {
627                     Log.e(LOG_TAG, "Couldn't launch image browser", e);
628                 }
629             }
630         });
631
632         final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
633         musicButton.setOnClickListener(new View.OnClickListener() {
634             public void onClick(View v) {
635                 try {
636                     startActivity(new Intent(MUSIC_NOW_PLAYING));
637                 } catch (android.content.ActivityNotFoundException e) {
638                     Log.e(LOG_TAG, "Couldn't launch music browser", e);
639                 }
640             }
641         });
642
643         final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
644         homeButton.setOnClickListener(new View.OnClickListener() {
645             public void onClick(View v) {
646                 startActivity(
647                     new Intent(Intent.ACTION_MAIN)
648                         .addCategory(Intent.CATEGORY_HOME));
649             }
650         });
651
652         final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
653         nightmodeButton.setOnClickListener(new View.OnClickListener() {
654             public void onClick(View v) {
655                 mDimmed = ! mDimmed;
656                 doDim(true);
657             }
658         });
659
660         nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
661             public boolean onLongClick(View v) {
662                 saveScreen();
663                 return true;
664             }
665         });
666
667         final View weatherView = findViewById(R.id.weather);
668         weatherView.setOnClickListener(new View.OnClickListener() {
669             public void onClick(View v) {
670                 if (!supportsWeather()) return;
671
672                 Intent genieAppQuery = getPackageManager().getLaunchIntentForPackage(GENIE_PACKAGE_ID);
673                 if (genieAppQuery != null) {
674                     startActivity(genieAppQuery);
675                 }
676             }
677         });
678     }
679
680     @Override
681     public void onConfigurationChanged(Configuration newConfig) {
682         super.onConfigurationChanged(newConfig);
683         if (!mScreenSaverMode) {
684             initViews();
685             doDim(false);
686             refreshAll();
687         }
688     }
689
690     @Override
691     public boolean onOptionsItemSelected(MenuItem item) {
692         if (item.getItemId() == R.id.menu_item_alarms) {
693             startActivity(new Intent(DeskClock.this, AlarmClock.class));
694             return true;
695         }
696         return false;
697     }
698
699     @Override
700     public boolean onCreateOptionsMenu(Menu menu) {
701         MenuInflater inflater = getMenuInflater();
702         inflater.inflate(R.menu.desk_clock_menu, menu);
703         return true;
704     }
705
706     @Override
707     protected void onCreate(Bundle icicle) {
708         super.onCreate(icicle);
709
710         mRNG = new Random();
711
712         try {
713             mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
714         } catch (PackageManager.NameNotFoundException e) {
715             // no weather info available
716             Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
717         }
718
719         initViews();
720     }
721
722 }