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