OSDN Git Service

Re-schedule screen saver mode when returning to normal.
[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 Random mRNG;
171
172     private PendingIntent mMidnightIntent;
173
174     private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
175         @Override
176         public void onReceive(Context context, Intent intent) {
177             final String action = intent.getAction();
178             if (Intent.ACTION_DATE_CHANGED.equals(action)) {
179                 refreshDate();
180             } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
181                 handleBatteryUpdate(
182                     intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
183                     intent.getIntExtra("level", 0));
184             } else if (Intent.ACTION_DOCK_EVENT.equals(action)) {
185                 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, -1);
186                 if (DEBUG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT, state=" + state);
187                 if (state == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
188                     if (mLaunchedFromDock) {
189                         // moveTaskToBack(false);
190                         finish();
191                     }
192                     mLaunchedFromDock = false;
193                 }
194             }
195         }
196     };
197
198     private final Handler mHandy = new Handler() {
199         @Override
200         public void handleMessage(Message m) {
201             if (m.what == QUERY_WEATHER_DATA_MSG) {
202                 new Thread() { public void run() { queryWeatherData(); } }.start();
203                 scheduleWeatherQueryDelayed(QUERY_WEATHER_DELAY);
204             } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
205                 updateWeatherDisplay();
206             } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
207                 saveScreen();
208             } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
209                 moveScreenSaver();
210             }
211         }
212     };
213
214
215     private void moveScreenSaver() {
216         moveScreenSaverTo(-1,-1);
217     }
218     private void moveScreenSaverTo(int x, int y) {
219         if (!mScreenSaverMode) return;
220
221         final View saver_view = findViewById(R.id.saver_view);
222
223         DisplayMetrics metrics = new DisplayMetrics();
224         getWindowManager().getDefaultDisplay().getMetrics(metrics);
225
226         if (x < 0 || y < 0) {
227             int myWidth = saver_view.getMeasuredWidth();
228             int myHeight = saver_view.getMeasuredHeight();
229             x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
230             y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
231         }
232
233         if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
234                 System.currentTimeMillis(), x, y));
235
236         saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams(
237             ViewGroup.LayoutParams.WRAP_CONTENT,
238             ViewGroup.LayoutParams.WRAP_CONTENT,
239             x,
240             y));
241
242         // Synchronize our jumping so that it happens exactly on the second.
243         mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
244             SCREEN_SAVER_MOVE_DELAY +
245             (1000 - (System.currentTimeMillis() % 1000)));
246     }
247
248     private void setWakeLock(boolean hold) {
249         if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
250         Window win = getWindow();
251         WindowManager.LayoutParams winParams = win.getAttributes();
252         winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
253         winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
254         winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
255         if (hold)
256             winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
257         else
258             winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
259         win.setAttributes(winParams);
260     }
261
262     private void scheduleScreenSaver() {
263         // reschedule screen saver
264         mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
265         mHandy.sendMessageDelayed(
266             Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG),
267             SCREEN_SAVER_TIMEOUT);
268     }
269
270     private void restoreScreen() {
271         if (!mScreenSaverMode) return;
272         if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
273         mScreenSaverMode = false;
274         initViews();
275         doDim(false); // restores previous dim mode
276         // policy: update weather info when returning from screen saver
277         if (mPluggedIn) requestWeatherDataFetch();
278
279         scheduleScreenSaver();
280
281         refreshAll();
282     }
283
284     // Special screen-saver mode for OLED displays that burn in quickly
285     private void saveScreen() {
286         if (mScreenSaverMode) return;
287         if (DEBUG) Log.d(LOG_TAG, "saveScreen");
288
289         // quickly stash away the x/y of the current date
290         final View oldTimeDate = findViewById(R.id.time_date);
291         int oldLoc[] = new int[2];
292         oldTimeDate.getLocationOnScreen(oldLoc);
293
294         mScreenSaverMode = true;
295         Window win = getWindow();
296         WindowManager.LayoutParams winParams = win.getAttributes();
297         winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
298         win.setAttributes(winParams);
299
300         // give up any internal focus before we switch layouts
301         final View focused = getCurrentFocus();
302         if (focused != null) focused.clearFocus();
303
304         setContentView(R.layout.desk_clock_saver);
305
306         mTime = (DigitalClock) findViewById(R.id.time);
307         mDate = (TextView) findViewById(R.id.date);
308         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
309
310         final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
311
312         ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
313         ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
314         mDate.setTextColor(color);
315         mNextAlarm.setTextColor(color);
316         mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
317             getResources().getDrawable(mDimmed
318                 ? R.drawable.ic_lock_idle_alarm_saver_dim
319                 : R.drawable.ic_lock_idle_alarm_saver),
320             null, null, null);
321
322         mBatteryDisplay =
323         mWeatherCurrentTemperature =
324         mWeatherHighTemperature =
325         mWeatherLowTemperature =
326         mWeatherLocation = null;
327         mWeatherIcon = null;
328
329         refreshDate();
330         refreshAlarm();
331
332         moveScreenSaverTo(oldLoc[0], oldLoc[1]);
333     }
334
335     @Override
336     public void onUserInteraction() {
337         if (mScreenSaverMode)
338             restoreScreen();
339     }
340
341     // Tell the Genie widget to load new data from the network.
342     private void requestWeatherDataFetch() {
343         if (DEBUG) Log.d(LOG_TAG, "forcing the Genie widget to update weather now...");
344         sendBroadcast(new Intent(ACTION_GENIE_REFRESH).putExtra("requestWeather", true));
345         // update the display with any new data
346         scheduleWeatherQueryDelayed(5000);
347     }
348
349     private boolean supportsWeather() {
350         return (mGenieResources != null);
351     }
352
353     private void scheduleWeatherQueryDelayed(long delay) {
354         // cancel any existing scheduled queries
355         unscheduleWeatherQuery();
356
357         if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
358
359         mHandy.sendEmptyMessageDelayed(QUERY_WEATHER_DATA_MSG, delay);
360     }
361
362     private void unscheduleWeatherQuery() {
363         mHandy.removeMessages(QUERY_WEATHER_DATA_MSG);
364     }
365
366     private void queryWeatherData() {
367         // if we couldn't load the weather widget's resources, we simply
368         // assume it's not present on the device.
369         if (mGenieResources == null) return;
370
371         Uri queryUri = new Uri.Builder()
372             .scheme(android.content.ContentResolver.SCHEME_CONTENT)
373             .authority(WEATHER_CONTENT_AUTHORITY)
374             .path(WEATHER_CONTENT_PATH)
375             .appendPath(new Long(System.currentTimeMillis()).toString())
376             .build();
377
378         if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
379
380         Cursor cur;
381         try {
382             cur = managedQuery(
383                 queryUri,
384                 WEATHER_CONTENT_COLUMNS,
385                 null,
386                 null,
387                 null);
388         } catch (RuntimeException e) {
389             Log.e(LOG_TAG, "Weather query failed", e);
390             cur = null;
391         }
392
393         if (cur != null && cur.moveToFirst()) {
394             if (DEBUG) {
395                 java.lang.StringBuilder sb =
396                     new java.lang.StringBuilder("Weather query result: {");
397                 for(int i=0; i<cur.getColumnCount(); i++) {
398                     if (i>0) sb.append(", ");
399                     sb.append(cur.getColumnName(i))
400                         .append("=")
401                         .append(cur.getString(i));
402                 }
403                 sb.append("}");
404                 Log.d(LOG_TAG, sb.toString());
405             }
406
407             mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
408                 cur.getColumnIndexOrThrow("iconResId")));
409             mWeatherCurrentTemperatureString = String.format("%d\u00b0",
410                 (cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
411             mWeatherHighTemperatureString = String.format("%d\u00b0",
412                 (cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
413             mWeatherLowTemperatureString = String.format("%d\u00b0",
414                 (cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
415             mWeatherLocationString = cur.getString(
416                 cur.getColumnIndexOrThrow("location"));
417         } else {
418             Log.w(LOG_TAG, "No weather information available (cur="
419                 + cur +")");
420             mWeatherIconDrawable = null;
421             mWeatherHighTemperatureString = "";
422             mWeatherLowTemperatureString = "";
423             mWeatherLocationString = getString(R.string.weather_fetch_failure);
424         }
425
426         mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
427     }
428
429     private void refreshWeather() {
430         if (supportsWeather())
431             scheduleWeatherQueryDelayed(0);
432         updateWeatherDisplay(); // in case we have it cached
433     }
434
435     private void updateWeatherDisplay() {
436         if (mWeatherCurrentTemperature == null) return;
437
438         mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
439         mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
440         mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
441         mWeatherLocation.setText(mWeatherLocationString);
442         mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
443     }
444
445     // Adapted from KeyguardUpdateMonitor.java
446     private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
447         final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
448         if (pluggedIn != mPluggedIn) {
449             setWakeLock(pluggedIn);
450
451             if (pluggedIn) {
452                 // policy: update weather info when attaching to power
453                 requestWeatherDataFetch();
454             }
455         }
456         if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
457             mBatteryLevel = batteryLevel;
458             mPluggedIn = pluggedIn;
459             refreshBattery();
460         }
461     }
462
463     private void refreshBattery() {
464         if (mBatteryDisplay == null) return;
465
466         if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
467             mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
468                 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
469             mBatteryDisplay.setText(
470                 getString(R.string.battery_charging_level, mBatteryLevel));
471             mBatteryDisplay.setVisibility(View.VISIBLE);
472         } else {
473             mBatteryDisplay.setVisibility(View.INVISIBLE);
474         }
475     }
476
477     private void refreshDate() {
478         final Date now = new Date();
479         if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
480         mDate.setText(DateFormat.format(mDateFormat, now));
481     }
482
483     private void refreshAlarm() {
484         if (mNextAlarm == null) return;
485
486         String nextAlarm = Settings.System.getString(getContentResolver(),
487                 Settings.System.NEXT_ALARM_FORMATTED);
488         if (!TextUtils.isEmpty(nextAlarm)) {
489             mNextAlarm.setText(nextAlarm);
490             //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
491             //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
492             mNextAlarm.setVisibility(View.VISIBLE);
493         } else {
494             mNextAlarm.setVisibility(View.INVISIBLE);
495         }
496     }
497
498     private void refreshAll() {
499         refreshDate();
500         refreshAlarm();
501         refreshBattery();
502         refreshWeather();
503     }
504
505     private void doDim(boolean fade) {
506         View tintView = findViewById(R.id.window_tint);
507         if (tintView == null) return;
508
509         Window win = getWindow();
510         WindowManager.LayoutParams winParams = win.getAttributes();
511
512         winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
513         winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
514
515         // dim the wallpaper somewhat (how much is determined below)
516         winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
517
518         if (mDimmed) {
519             winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
520             winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED;
521
522             // show the window tint
523             tintView.startAnimation(AnimationUtils.loadAnimation(this,
524                 fade ? R.anim.dim
525                      : R.anim.dim_instant));
526         } else {
527             winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
528             winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL;
529
530             // hide the window tint
531             tintView.startAnimation(AnimationUtils.loadAnimation(this,
532                 fade ? R.anim.undim
533                      : R.anim.undim_instant));
534         }
535
536         win.setAttributes(winParams);
537     }
538
539     @Override
540     public void onNewIntent(Intent newIntent) {
541         super.onNewIntent(newIntent);
542         if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
543
544         // update our intent so that we can consult it to determine whether or
545         // not the most recent launch was via a dock event 
546         setIntent(newIntent);
547     }
548
549     @Override
550     public void onResume() {
551         super.onResume();
552         if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent());
553
554         // reload the date format in case the user has changed settings
555         // recently
556         mDateFormat = getString(com.android.internal.R.string.full_wday_month_day_no_year);
557
558         IntentFilter filter = new IntentFilter();
559         filter.addAction(Intent.ACTION_DATE_CHANGED);
560         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
561         filter.addAction(Intent.ACTION_DOCK_EVENT);
562         filter.addAction(ACTION_MIDNIGHT);
563         registerReceiver(mIntentReceiver, filter);
564
565         Calendar today = Calendar.getInstance();
566         today.add(Calendar.DATE, 1);
567         mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
568         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
569         am.setRepeating(AlarmManager.RTC, today.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mMidnightIntent);
570
571         // un-dim when resuming
572         mDimmed = false;
573         doDim(false);
574
575         restoreScreen(); // disable screen saver
576         refreshAll(); // will schedule periodic weather fetch
577
578         setWakeLock(mPluggedIn);
579
580         scheduleScreenSaver();
581
582         final boolean launchedFromDock
583             = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
584
585         if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) {
586             // policy: fetch weather if launched via dock connection
587             if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
588             requestWeatherDataFetch();
589         }
590
591         mLaunchedFromDock = launchedFromDock;
592     }
593
594     @Override
595     public void onPause() {
596         if (DEBUG) Log.d(LOG_TAG, "onPause");
597
598         // Turn off the screen saver and cancel any pending timeouts.
599         // (But don't un-dim.)
600         mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
601         restoreScreen();
602
603         // Other things we don't want to be doing in the background.
604         unregisterReceiver(mIntentReceiver);
605         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
606         am.cancel(mMidnightIntent);
607         unscheduleWeatherQuery();
608
609         super.onPause();
610     }
611
612     @Override
613     public void onStop() {
614         if (DEBUG) Log.d(LOG_TAG, "onStop");
615
616         // Avoid situations where the user launches Alarm Clock and is
617         // surprised to find it in dim mode (because it was last used in dim
618         // mode, but that last use is long in the past).
619         mDimmed = false;
620
621         super.onStop();
622     }
623
624     private void initViews() {
625         // give up any internal focus before we switch layouts
626         final View focused = getCurrentFocus();
627         if (focused != null) focused.clearFocus();
628
629         setContentView(R.layout.desk_clock);
630
631         mTime = (DigitalClock) findViewById(R.id.time);
632         mDate = (TextView) findViewById(R.id.date);
633         mBatteryDisplay = (TextView) findViewById(R.id.battery);
634
635         mTime.getRootView().requestFocus();
636
637         mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
638         mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
639         mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
640         mWeatherLocation = (TextView) findViewById(R.id.weather_location);
641         mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
642
643         final View.OnClickListener alarmClickListener = new View.OnClickListener() {
644             public void onClick(View v) {
645                 startActivity(new Intent(DeskClock.this, AlarmClock.class));
646             }
647         };
648
649         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
650         mNextAlarm.setOnClickListener(alarmClickListener);
651
652         final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
653         alarmButton.setOnClickListener(alarmClickListener);
654
655         final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
656         galleryButton.setOnClickListener(new View.OnClickListener() {
657             public void onClick(View v) {
658                 try {
659                     startActivity(new Intent(
660                         Intent.ACTION_VIEW,
661                         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
662                             .putExtra("slideshow", true)
663                             .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
664                 } catch (android.content.ActivityNotFoundException e) {
665                     Log.e(LOG_TAG, "Couldn't launch image browser", e);
666                 }
667             }
668         });
669
670         final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
671         musicButton.setOnClickListener(new View.OnClickListener() {
672             public void onClick(View v) {
673                 try {
674                     Intent musicAppQuery = getPackageManager()
675                         .getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
676                         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
677                     if (musicAppQuery != null) {
678                         startActivity(musicAppQuery);
679                     }
680                 } catch (android.content.ActivityNotFoundException e) {
681                     Log.e(LOG_TAG, "Couldn't launch music browser", e);
682                 }
683             }
684         });
685
686         final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
687         homeButton.setOnClickListener(new View.OnClickListener() {
688             public void onClick(View v) {
689                 startActivity(
690                     new Intent(Intent.ACTION_MAIN)
691                         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)
692                         .addCategory(Intent.CATEGORY_HOME));
693             }
694         });
695
696         final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
697         nightmodeButton.setOnClickListener(new View.OnClickListener() {
698             public void onClick(View v) {
699                 mDimmed = ! mDimmed;
700                 doDim(true);
701             }
702         });
703
704         nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
705             public boolean onLongClick(View v) {
706                 saveScreen();
707                 return true;
708             }
709         });
710
711         final View weatherView = findViewById(R.id.weather);
712         weatherView.setOnClickListener(new View.OnClickListener() {
713             public void onClick(View v) {
714                 if (!supportsWeather()) return;
715
716                 Intent genieAppQuery = getPackageManager()
717                     .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
718                     .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
719                 if (genieAppQuery != null) {
720                     startActivity(genieAppQuery);
721                 }
722             }
723         });
724     }
725
726     @Override
727     public void onConfigurationChanged(Configuration newConfig) {
728         super.onConfigurationChanged(newConfig);
729         if (!mScreenSaverMode) {
730             initViews();
731             doDim(false);
732             refreshAll();
733         }
734     }
735
736     @Override
737     public boolean onOptionsItemSelected(MenuItem item) {
738         if (item.getItemId() == R.id.menu_item_alarms) {
739             startActivity(new Intent(DeskClock.this, AlarmClock.class));
740             return true;
741         } else if (item.getItemId() == R.id.menu_item_add_alarm) {
742             AlarmClock.addNewAlarm(this);
743             return true;
744         }
745         return false;
746     }
747
748     @Override
749     public boolean onCreateOptionsMenu(Menu menu) {
750         MenuInflater inflater = getMenuInflater();
751         inflater.inflate(R.menu.desk_clock_menu, menu);
752         return true;
753     }
754
755     @Override
756     protected void onCreate(Bundle icicle) {
757         super.onCreate(icicle);
758
759         mRNG = new Random();
760
761         try {
762             mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
763         } catch (PackageManager.NameNotFoundException e) {
764             // no weather info available
765             Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
766         }
767
768         initViews();
769     }
770
771 }