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