OSDN Git Service

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