OSDN Git Service

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