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