OSDN Git Service

am 2ff01ef6: Fine-tuning the DeskClock UI.
[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 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 String 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 saver_view = findViewById(R.id.saver_view);
214
215         DisplayMetrics metrics = new DisplayMetrics();
216         getWindowManager().getDefaultDisplay().getMetrics(metrics);
217
218         if (x < 0 || y < 0) {
219             int myWidth = saver_view.getMeasuredWidth();
220             int myHeight = saver_view.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         saver_view.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         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
288
289         final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
290
291         ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
292         ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
293         mDate.setTextColor(color);
294         mNextAlarm.setTextColor(color);
295         mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
296             getResources().getDrawable(mDimmed 
297                 ? R.drawable.ic_lock_idle_alarm_saver_dim 
298                 : R.drawable.ic_lock_idle_alarm_saver),
299             null, null, null);
300
301         mBatteryDisplay =
302         mWeatherCurrentTemperature =
303         mWeatherHighTemperature =
304         mWeatherLowTemperature =
305         mWeatherLocation = null;
306         mWeatherIcon = null;
307
308         refreshDate();
309         refreshAlarm();
310
311         moveScreenSaverTo(oldLoc[0], oldLoc[1]);
312     }
313
314     @Override
315     public void onUserInteraction() {
316         if (mScreenSaverMode)
317             restoreScreen();
318     }
319
320     private boolean supportsWeather() {
321         return (mGenieResources != null);
322     }
323
324     private void scheduleWeatherFetchDelayed(long delay) {
325         if (mWeatherFetchScheduled) return;
326
327         if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
328
329         mWeatherFetchScheduled = true;
330
331         mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
332     }
333
334     private void unscheduleWeatherFetch() {
335         mWeatherFetchScheduled = false;
336     }
337
338     private void fetchWeatherData() {
339         // if we couldn't load the weather widget's resources, we simply
340         // assume it's not present on the device.
341         if (mGenieResources == null) return;
342
343         Uri queryUri = new Uri.Builder()
344             .scheme(android.content.ContentResolver.SCHEME_CONTENT)
345             .authority(WEATHER_CONTENT_AUTHORITY)
346             .path(WEATHER_CONTENT_PATH)
347             .appendPath(new Long(System.currentTimeMillis()).toString())
348             .build();
349
350         if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
351
352         Cursor cur;
353         try {
354             cur = managedQuery(
355                 queryUri,
356                 WEATHER_CONTENT_COLUMNS,
357                 null,
358                 null,
359                 null);
360         } catch (RuntimeException e) {
361             Log.e(LOG_TAG, "Weather query failed", e);
362             cur = null;
363         }
364
365         if (cur != null && cur.moveToFirst()) {
366             if (DEBUG) {
367                 java.lang.StringBuilder sb =
368                     new java.lang.StringBuilder("Weather query result: {");
369                 for(int i=0; i<cur.getColumnCount(); i++) {
370                     if (i>0) sb.append(", ");
371                     sb.append(cur.getColumnName(i))
372                         .append("=")
373                         .append(cur.getString(i));
374                 }
375                 sb.append("}");
376                 Log.d(LOG_TAG, sb.toString());
377             }
378
379             mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
380                 cur.getColumnIndexOrThrow("iconResId")));
381             mWeatherCurrentTemperatureString = String.format("%d\u00b0",
382                 (cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
383             mWeatherHighTemperatureString = String.format("%d\u00b0",
384                 (cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
385             mWeatherLowTemperatureString = String.format("%d\u00b0",
386                 (cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
387             mWeatherLocationString = cur.getString(
388                 cur.getColumnIndexOrThrow("location"));
389         } else {
390             Log.w(LOG_TAG, "No weather information available (cur="
391                 + cur +")");
392             mWeatherIconDrawable = null;
393             mWeatherHighTemperatureString = "";
394             mWeatherLowTemperatureString = "";
395             mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
396         }
397
398         mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
399     }
400
401     private void refreshWeather() {
402         if (supportsWeather())
403             scheduleWeatherFetchDelayed(0);
404         updateWeatherDisplay(); // in case we have it cached
405     }
406
407     private void updateWeatherDisplay() {
408         if (mWeatherCurrentTemperature == null) return;
409
410         mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
411         mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
412         mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
413         mWeatherLocation.setText(mWeatherLocationString);
414         mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
415     }
416
417     // Adapted from KeyguardUpdateMonitor.java
418     private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
419         final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
420         if (pluggedIn != mPluggedIn) {
421             setWakeLock(pluggedIn);
422         }
423         if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
424             mBatteryLevel = batteryLevel;
425             mPluggedIn = pluggedIn;
426             refreshBattery();
427         }
428     }
429
430     private void refreshBattery() {
431         if (mBatteryDisplay == null) return;
432
433         if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
434             mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
435                 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
436             mBatteryDisplay.setText(
437                 getString(R.string.battery_charging_level, mBatteryLevel));
438             mBatteryDisplay.setVisibility(View.VISIBLE);
439         } else {
440             mBatteryDisplay.setVisibility(View.INVISIBLE);
441         }
442     }
443
444     private void refreshDate() {
445         final Date now = new Date();
446         if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
447         mDate.setText(DateFormat.format(mDateFormat, now));
448     }
449
450     private void refreshAlarm() {
451         if (mNextAlarm == null) return;
452
453         String nextAlarm = Settings.System.getString(getContentResolver(),
454                 Settings.System.NEXT_ALARM_FORMATTED);
455         if (!TextUtils.isEmpty(nextAlarm)) {
456             mNextAlarm.setText(nextAlarm);
457             //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
458             //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
459             mNextAlarm.setVisibility(View.VISIBLE);
460         } else {
461             mNextAlarm.setVisibility(View.INVISIBLE);
462         }
463     }
464
465     private void refreshAll() {
466         refreshDate();
467         refreshAlarm();
468         refreshBattery();
469         refreshWeather();
470     }
471
472     private void doDim(boolean fade) {
473         View tintView = findViewById(R.id.window_tint);
474         if (tintView == null) return;
475
476         Window win = getWindow();
477         WindowManager.LayoutParams winParams = win.getAttributes();
478
479         winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
480         winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
481
482         // dim the wallpaper somewhat (how much is determined below)
483         winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
484
485         if (mDimmed) {
486             winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
487             winParams.dimAmount = 0.67f; // pump up contrast in dim mode
488
489             // show the window tint
490             tintView.startAnimation(AnimationUtils.loadAnimation(this,
491                 fade ? R.anim.dim
492                      : R.anim.dim_instant));
493         } else {
494             winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
495             winParams.dimAmount = 0.5f; // lower contrast in normal mode
496
497             // hide the window tint
498             tintView.startAnimation(AnimationUtils.loadAnimation(this,
499                 fade ? R.anim.undim
500                      : R.anim.undim_instant));
501         }
502
503         win.setAttributes(winParams);
504     }
505
506     @Override
507     public void onResume() {
508         super.onResume();
509         if (DEBUG) Log.d(LOG_TAG, "onResume");
510
511         // reload the date format in case the user has changed settings
512         // recently
513         mDateFormat = getString(com.android.internal.R.string.full_wday_month_day_no_year);
514
515         IntentFilter filter = new IntentFilter();
516         filter.addAction(Intent.ACTION_DATE_CHANGED);
517         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
518         filter.addAction(ACTION_MIDNIGHT);
519
520         Calendar today = Calendar.getInstance();
521         today.add(Calendar.DATE, 1);
522         mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
523         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
524         am.setRepeating(AlarmManager.RTC, today.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mMidnightIntent);
525         registerReceiver(mIntentReceiver, filter);
526
527         doDim(false);
528         restoreScreen();
529         refreshAll(); // will schedule periodic weather fetch
530
531         setWakeLock(mPluggedIn);
532
533         mIdleTimeoutEpoch++;
534         mHandy.sendMessageDelayed(
535             Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
536             SCREEN_SAVER_TIMEOUT);
537
538         final boolean launchedFromDock 
539             = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
540
541         if (supportsWeather() && launchedFromDock && !mInDock) {
542             if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
543             sendBroadcast(
544                 new Intent("com.google.android.apps.genie.REFRESH")
545                     .putExtra("requestWeather", true));
546         }
547
548         mInDock = launchedFromDock;
549     }
550
551     @Override
552     public void onPause() {
553         if (DEBUG) Log.d(LOG_TAG, "onPause");
554
555         // Turn off the screen saver. (But don't un-dim.)
556         restoreScreen();
557
558         // Other things we don't want to be doing in the background.
559         unregisterReceiver(mIntentReceiver);
560         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
561         am.cancel(mMidnightIntent);
562         unscheduleWeatherFetch();
563
564         super.onPause();
565     }
566
567     @Override
568     public void onStop() {
569         if (DEBUG) Log.d(LOG_TAG, "onStop");
570
571         // Avoid situations where the user launches Alarm Clock and is
572         // surprised to find it in dim mode (because it was last used in dim
573         // mode, but that last use is long in the past).
574         mDimmed = false;
575
576         super.onStop();
577     }
578
579     private void initViews() {
580         // give up any internal focus before we switch layouts
581         final View focused = getCurrentFocus();
582         if (focused != null) focused.clearFocus();
583
584         setContentView(R.layout.desk_clock);
585
586         mTime = (DigitalClock) findViewById(R.id.time);
587         mDate = (TextView) findViewById(R.id.date);
588         mBatteryDisplay = (TextView) findViewById(R.id.battery);
589
590         mTime.getRootView().requestFocus();
591
592         mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
593         mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
594         mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
595         mWeatherLocation = (TextView) findViewById(R.id.weather_location);
596         mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
597
598         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
599
600         final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
601         alarmButton.setOnClickListener(new View.OnClickListener() {
602             public void onClick(View v) {
603                 startActivity(new Intent(DeskClock.this, AlarmClock.class));
604             }
605         });
606
607         final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
608         galleryButton.setOnClickListener(new View.OnClickListener() {
609             public void onClick(View v) {
610                 try {
611                     startActivity(new Intent(
612                         Intent.ACTION_VIEW,
613                         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
614                             .putExtra("slideshow", true)
615                             .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
616                 } catch (android.content.ActivityNotFoundException e) {
617                     Log.e(LOG_TAG, "Couldn't launch image browser", e);
618                 }
619             }
620         });
621
622         final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
623         musicButton.setOnClickListener(new View.OnClickListener() {
624             public void onClick(View v) {
625                 try {
626                     Intent musicAppQuery = getPackageManager()
627                         .getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
628                         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
629                     if (musicAppQuery != null) {
630                         startActivity(musicAppQuery);
631                     }
632                 } catch (android.content.ActivityNotFoundException e) {
633                     Log.e(LOG_TAG, "Couldn't launch music browser", e);
634                 }
635             }
636         });
637
638         final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
639         homeButton.setOnClickListener(new View.OnClickListener() {
640             public void onClick(View v) {
641                 startActivity(
642                     new Intent(Intent.ACTION_MAIN)
643                         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
644                         .addCategory(Intent.CATEGORY_HOME));
645             }
646         });
647
648         final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
649         nightmodeButton.setOnClickListener(new View.OnClickListener() {
650             public void onClick(View v) {
651                 mDimmed = ! mDimmed;
652                 doDim(true);
653             }
654         });
655
656         nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
657             public boolean onLongClick(View v) {
658                 saveScreen();
659                 return true;
660             }
661         });
662
663         final View weatherView = findViewById(R.id.weather);
664         weatherView.setOnClickListener(new View.OnClickListener() {
665             public void onClick(View v) {
666                 if (!supportsWeather()) return;
667
668                 Intent genieAppQuery = getPackageManager()
669                     .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
670                     .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
671                 if (genieAppQuery != null) {
672                     startActivity(genieAppQuery);
673                 }
674             }
675         });
676     }
677
678     @Override
679     public void onConfigurationChanged(Configuration newConfig) {
680         super.onConfigurationChanged(newConfig);
681         if (!mScreenSaverMode) {
682             initViews();
683             doDim(false);
684             refreshAll();
685         }
686     }
687
688     @Override
689     public boolean onOptionsItemSelected(MenuItem item) {
690         if (item.getItemId() == R.id.menu_item_alarms) {
691             startActivity(new Intent(DeskClock.this, AlarmClock.class));
692             return true;
693         }
694         return false;
695     }
696
697     @Override
698     public boolean onCreateOptionsMenu(Menu menu) {
699         MenuInflater inflater = getMenuInflater();
700         inflater.inflate(R.menu.desk_clock_menu, menu);
701         return true;
702     }
703
704     @Override
705     protected void onCreate(Bundle icicle) {
706         super.onCreate(icicle);
707
708         mRNG = new Random();
709
710         try {
711             mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
712         } catch (PackageManager.NameNotFoundException e) {
713             // no weather info available
714             Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
715         }
716
717         initViews();
718     }
719
720 }