OSDN Git Service

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