DeskClock.java revision e6cf24dbbea56d8b88a8d48bed9d3a6f26c2ddf0
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.AlertDialog;
21import android.content.BroadcastReceiver;
22import android.content.Context;
23import android.content.DialogInterface;
24import android.content.Intent;
25import android.content.IntentFilter;
26import android.content.SharedPreferences;
27import android.content.pm.PackageManager;
28import android.content.res.Configuration;
29import android.content.res.Resources;
30import android.database.Cursor;
31import android.graphics.drawable.BitmapDrawable;
32import android.graphics.drawable.ColorDrawable;
33import android.graphics.drawable.Drawable;
34import android.net.Uri;
35import android.os.Bundle;
36import android.os.Handler;
37import android.os.Message;
38import android.os.SystemClock;
39import android.os.PowerManager;
40import android.provider.Settings;
41import android.text.TextUtils;
42import android.util.DisplayMetrics;
43import android.util.Log;
44import android.view.ContextMenu.ContextMenuInfo;
45import android.view.ContextMenu;
46import android.view.LayoutInflater;
47import android.view.Menu;
48import android.view.MenuItem;
49import android.view.View.OnClickListener;
50import android.view.View.OnCreateContextMenuListener;
51import android.view.View;
52import android.view.ViewGroup;
53import android.view.Window;
54import android.view.WindowManager;
55import android.view.animation.Animation;
56import android.view.animation.AnimationUtils;
57import android.view.animation.TranslateAnimation;
58import android.widget.AbsoluteLayout;
59import android.widget.AdapterView.AdapterContextMenuInfo;
60import android.widget.AdapterView.OnItemClickListener;
61import android.widget.AdapterView;
62import android.widget.Button;
63import android.widget.CheckBox;
64import android.widget.ImageView;
65import android.widget.TextView;
66
67import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
68import static android.os.BatteryManager.BATTERY_STATUS_FULL;
69import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
70
71import java.io.IOException;
72import java.io.InputStream;
73import java.text.DateFormat;
74import java.util.Date;
75import java.util.Locale;
76import java.util.Random;
77
78/**
79 * DeskClock clock view for desk docks.
80 */
81public class DeskClock extends Activity {
82    private static final boolean DEBUG = false;
83
84    private static final String LOG_TAG = "DeskClock";
85
86    private static final String MUSIC_NOW_PLAYING_ACTIVITY = "com.android.music.PLAYBACK_VIEWER";
87
88    private final long FETCH_WEATHER_DELAY = 60 * 60 * 1000; // 1 hr
89    private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min
90    private final long SCREEN_SAVER_MOVE_DELAY = 5 * 1000; // 15 sec
91
92    private final int FETCH_WEATHER_DATA_MSG     = 0x1000;
93    private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
94    private final int SCREEN_SAVER_TIMEOUT_MSG   = 0x2000;
95    private final int SCREEN_SAVER_MOVE_MSG      = 0x2001;
96
97    private final int SCREEN_SAVER_COLOR = 0xFF008000;
98    private final int SCREEN_SAVER_COLOR_DIM = 0xFF003000;
99
100    private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
101    private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
102    private static final String WEATHER_CONTENT_PATH = "/weather/current";
103    private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
104            "location",
105            "timestamp",
106            "highTemperature",
107            "lowTemperature",
108            "iconUrl",
109            "iconResId",
110            "description",
111        };
112
113    private DigitalClock mTime;
114    private TextView mDate;
115
116    private TextView mNextAlarm = null;
117    private TextView mBatteryDisplay;
118
119    private TextView mWeatherHighTemperature;
120    private TextView mWeatherLowTemperature;
121    private TextView mWeatherLocation;
122    private ImageView mWeatherIcon;
123
124    private String mWeatherHighTemperatureString;
125    private String mWeatherLowTemperatureString;
126    private String mWeatherLocationString;
127    private Drawable mWeatherIconDrawable;
128
129    private Resources mGenieResources = null;
130
131    private boolean mDimmed = false;
132    private boolean mScreenSaverMode = false;
133
134    private DateFormat mDateFormat;
135
136    private int mBatteryLevel = -1;
137    private boolean mPluggedIn = false;
138
139    private int mIdleTimeoutEpoch = 0;
140
141    private boolean mWeatherFetchScheduled = false;
142
143    private Random mRNG;
144
145    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
146        @Override
147        public void onReceive(Context context, Intent intent) {
148            final String action = intent.getAction();
149            if (Intent.ACTION_DATE_CHANGED.equals(action)) {
150                refreshDate();
151            } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
152                handleBatteryUpdate(
153                    intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
154                    intent.getIntExtra("level", 0));
155            }
156        }
157    };
158
159    private final Handler mHandy = new Handler() {
160        @Override
161        public void handleMessage(Message m) {
162            if (DEBUG) Log.d(LOG_TAG, "handleMessage: " + m.toString());
163
164            if (m.what == FETCH_WEATHER_DATA_MSG) {
165                if (!mWeatherFetchScheduled) return;
166                mWeatherFetchScheduled = false;
167                new Thread() { public void run() { fetchWeatherData(); } }.start();
168                scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
169            } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
170                updateWeatherDisplay();
171            } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
172                if (m.arg1 == mIdleTimeoutEpoch) {
173                    saveScreen();
174                }
175            } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
176                moveScreenSaver();
177            }
178        }
179    };
180    private void moveScreenSaver() {
181        moveScreenSaverTo(-1,-1);
182    }
183    private void moveScreenSaverTo(int x, int y) {
184        if (!mScreenSaverMode) return;
185
186        final View time_date = findViewById(R.id.time_date);
187
188        /*
189        final TranslateAnimation anim = new TranslateAnimation(
190            Animation.RELATIVE_TO_SELF,   0, // fromX
191            Animation.RELATIVE_TO_PARENT, 0.5f, // toX
192            Animation.RELATIVE_TO_SELF,   0, // fromY
193            Animation.RELATIVE_TO_PARENT, 0.5f // toY
194        );
195        anim.setDuration(1000);
196        anim.setInterpolator(new android.view.animation.AccelerateDecelerateInterpolator());
197        anim.setFillEnabled(true);
198        anim.setFillAfter(true);
199        time_date.startAnimation(anim);
200        */
201
202        DisplayMetrics metrics = new DisplayMetrics();
203        getWindowManager().getDefaultDisplay().getMetrics(metrics);
204
205        if (x < 0 || y < 0) {
206            int myWidth = time_date.getMeasuredWidth();
207            int myHeight = time_date.getMeasuredHeight();
208            x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
209            y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
210        }
211
212        time_date.setLayoutParams(new AbsoluteLayout.LayoutParams(
213            ViewGroup.LayoutParams.WRAP_CONTENT,
214            ViewGroup.LayoutParams.WRAP_CONTENT,
215            x,
216            y));
217
218        mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG, SCREEN_SAVER_MOVE_DELAY);
219    }
220
221    private void setWakeLock(boolean hold) {
222        if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
223        Window win = getWindow();
224        WindowManager.LayoutParams winParams = win.getAttributes();
225        winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
226        if (hold)
227            winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
228        else
229            winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
230        win.setAttributes(winParams);
231    }
232
233    private void restoreScreen() {
234        if (!mScreenSaverMode) return;
235        mScreenSaverMode = false;
236        initViews();
237        doDim(false); // restores previous dim mode
238        refreshAll();
239    }
240
241    // Special screen-saver mode for OLED displays that burn in quickly
242    private void saveScreen() {
243        if (mScreenSaverMode) return;
244
245        // quickly stash away the x/y of the current date
246        final View oldTimeDate = findViewById(R.id.time_date);
247        int oldLoc[] = new int[2];
248        oldTimeDate.getLocationOnScreen(oldLoc);
249
250        mScreenSaverMode = true;
251        Window win = getWindow();
252        WindowManager.LayoutParams winParams = win.getAttributes();
253        winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
254        win.setAttributes(winParams);
255
256        // give up any internal focus before we switch layouts
257        final View focused = getCurrentFocus();
258        if (focused != null) focused.clearFocus();
259
260        setContentView(R.layout.desk_clock_saver);
261
262        mTime = (DigitalClock) findViewById(R.id.time);
263        mDate = (TextView) findViewById(R.id.date);
264
265        final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
266
267        ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
268        ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
269        mDate.setTextColor(color);
270
271        mBatteryDisplay =
272        mNextAlarm =
273        mWeatherHighTemperature =
274        mWeatherLowTemperature =
275        mWeatherLocation = null;
276        mWeatherIcon = null;
277
278        refreshDate();
279
280        moveScreenSaverTo(oldLoc[0], oldLoc[1]);
281    }
282
283    @Override
284    public void onUserInteraction() {
285        if (mScreenSaverMode)
286            restoreScreen();
287    }
288
289    private boolean supportsWeather() {
290        return (mGenieResources != null);
291    }
292
293    private void scheduleWeatherFetchDelayed(long delay) {
294        if (mWeatherFetchScheduled) return;
295
296        if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
297
298        mWeatherFetchScheduled = true;
299
300        mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
301    }
302
303    private void unscheduleWeatherFetch() {
304        mWeatherFetchScheduled = false;
305    }
306
307    private static final boolean sCelsius;
308    static {
309        String cc = Locale.getDefault().getCountry().toLowerCase();
310        sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
311    }
312
313    private static int celsiusToLocal(int tempC) {
314        return sCelsius ? tempC : (int)(tempC * 1.8f + 32);
315    }
316
317    private void fetchWeatherData() {
318        // if we couldn't load the weather widget's resources, we simply
319        // assume it's not present on the device.
320        if (mGenieResources == null) return;
321
322        Uri queryUri = new Uri.Builder()
323            .scheme(android.content.ContentResolver.SCHEME_CONTENT)
324            .authority(WEATHER_CONTENT_AUTHORITY)
325            .path(WEATHER_CONTENT_PATH)
326            .appendPath(new Long(System.currentTimeMillis()).toString())
327            .build();
328
329        if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
330
331        Cursor cur;
332        try {
333            cur = managedQuery(
334                queryUri,
335                WEATHER_CONTENT_COLUMNS,
336                null,
337                null,
338                null);
339        } catch (RuntimeException e) {
340            Log.e(LOG_TAG, "Weather query failed", e);
341            cur = null;
342        }
343
344        if (cur != null && cur.moveToFirst()) {
345            mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
346                cur.getColumnIndexOrThrow("iconResId")));
347            mWeatherHighTemperatureString = String.format("%d\u00b0",
348                celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
349            mWeatherLowTemperatureString = String.format("%d\u00b0",
350                celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
351            mWeatherLocationString = cur.getString(
352                cur.getColumnIndexOrThrow("location"));
353        } else {
354            Log.w(LOG_TAG, "No weather information available (cur="
355                + cur +")");
356            mWeatherIconDrawable = null;
357            mWeatherHighTemperatureString = "";
358            mWeatherLowTemperatureString = "";
359            mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
360        }
361
362        mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
363    }
364
365    private void refreshWeather() {
366        if (supportsWeather())
367            scheduleWeatherFetchDelayed(0);
368        updateWeatherDisplay(); // in case we have it cached
369    }
370
371    private void updateWeatherDisplay() {
372        if (mWeatherHighTemperature == null) return;
373
374        mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
375        mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
376        mWeatherLocation.setText(mWeatherLocationString);
377        mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
378    }
379
380    // Adapted from KeyguardUpdateMonitor.java
381    private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
382        final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
383        if (pluggedIn != mPluggedIn) {
384            setWakeLock(pluggedIn);
385        }
386        if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
387            mBatteryLevel = batteryLevel;
388            mPluggedIn = pluggedIn;
389            refreshBattery();
390        }
391    }
392
393    private void refreshBattery() {
394        if (mBatteryDisplay == null) return;
395
396        if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
397            mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
398                0, 0, android.R.drawable.ic_lock_idle_charging, 0);
399            mBatteryDisplay.setText(
400                getString(R.string.battery_charging_level, mBatteryLevel));
401            mBatteryDisplay.setVisibility(View.VISIBLE);
402        } else {
403            mBatteryDisplay.setVisibility(View.INVISIBLE);
404        }
405    }
406
407    private void refreshDate() {
408        mDate.setText(mDateFormat.format(new Date()));
409    }
410
411    private void refreshAlarm() {
412        if (mNextAlarm == null) return;
413
414        String nextAlarm = Settings.System.getString(getContentResolver(),
415                Settings.System.NEXT_ALARM_FORMATTED);
416        if (!TextUtils.isEmpty(nextAlarm)) {
417            mNextAlarm.setText(nextAlarm);
418            //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
419            //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
420            mNextAlarm.setVisibility(View.VISIBLE);
421        } else {
422            mNextAlarm.setVisibility(View.INVISIBLE);
423        }
424    }
425
426    private void refreshAll() {
427        refreshDate();
428        refreshAlarm();
429        refreshBattery();
430        refreshWeather();
431    }
432
433    private void doDim(boolean fade) {
434        View tintView = findViewById(R.id.window_tint);
435        if (tintView == null) return;
436
437        Window win = getWindow();
438        WindowManager.LayoutParams winParams = win.getAttributes();
439
440        // secret!
441        winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
442        winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
443
444        // dim the wallpaper somewhat (how much is determined below)
445        winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
446
447        if (mDimmed) {
448            winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
449            winParams.dimAmount = 0.5f; // pump up contrast in dim mode
450
451            // show the window tint
452            tintView.startAnimation(AnimationUtils.loadAnimation(this,
453                fade ? R.anim.dim
454                     : R.anim.dim_instant));
455        } else {
456            winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
457            winParams.dimAmount = 0.2f; // lower contrast in normal mode
458
459            // hide the window tint
460            tintView.startAnimation(AnimationUtils.loadAnimation(this,
461                fade ? R.anim.undim
462                     : R.anim.undim_instant));
463        }
464
465        win.setAttributes(winParams);
466    }
467
468    @Override
469    public void onResume() {
470        super.onResume();
471        // NB: To avoid situations where the user launches Alarm Clock and is
472        // surprised to find it in dim mode (because it was last used in dim
473        // mode, but that last use is long in the past), we always un-dim upon
474        // bringing the activity to the foregreound.
475        mDimmed = false;
476
477        // reload the date format in case the user has changed settings
478        // recently
479        mDateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
480
481        IntentFilter filter = new IntentFilter();
482        filter.addAction(Intent.ACTION_DATE_CHANGED);
483        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
484        registerReceiver(mIntentReceiver, filter);
485
486        doDim(false);
487        restoreScreen();
488        refreshAll();
489        setWakeLock(mPluggedIn);
490
491        mIdleTimeoutEpoch++;
492        mHandy.sendMessageDelayed(
493            Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
494            SCREEN_SAVER_TIMEOUT);
495    }
496
497    @Override
498    public void onPause() {
499        super.onPause();
500        unregisterReceiver(mIntentReceiver);
501        unscheduleWeatherFetch();
502    }
503
504
505    private void initViews() {
506        // give up any internal focus before we switch layouts
507        final View focused = getCurrentFocus();
508        if (focused != null) focused.clearFocus();
509
510        setContentView(R.layout.desk_clock);
511
512        mTime = (DigitalClock) findViewById(R.id.time);
513        mDate = (TextView) findViewById(R.id.date);
514        mBatteryDisplay = (TextView) findViewById(R.id.battery);
515
516        mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
517        mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
518        mWeatherLocation = (TextView) findViewById(R.id.weather_location);
519        mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
520
521        mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
522
523        final Button alarmButton = (Button) findViewById(R.id.alarm_button);
524        alarmButton.setOnClickListener(new View.OnClickListener() {
525            public void onClick(View v) {
526                startActivity(new Intent(DeskClock.this, AlarmClock.class));
527            }
528        });
529
530        final Button galleryButton = (Button) findViewById(R.id.gallery_button);
531        galleryButton.setOnClickListener(new View.OnClickListener() {
532            public void onClick(View v) {
533                try {
534                    startActivity(new Intent(
535                        Intent.ACTION_VIEW,
536                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
537                } catch (android.content.ActivityNotFoundException e) {
538                    Log.e(LOG_TAG, "Couldn't launch image browser", e);
539                }
540            }
541        });
542
543        final Button musicButton = (Button) findViewById(R.id.music_button);
544        musicButton.setOnClickListener(new View.OnClickListener() {
545            public void onClick(View v) {
546                try {
547                    startActivity(new Intent(MUSIC_NOW_PLAYING_ACTIVITY));
548                } catch (android.content.ActivityNotFoundException e) {
549                    Log.e(LOG_TAG, "Couldn't launch music browser", e);
550                }
551            }
552        });
553
554        final Button homeButton = (Button) findViewById(R.id.home_button);
555        homeButton.setOnClickListener(new View.OnClickListener() {
556            public void onClick(View v) {
557                startActivity(
558                    new Intent(Intent.ACTION_MAIN)
559                        .addCategory(Intent.CATEGORY_HOME));
560            }
561        });
562
563        final Button nightmodeButton = (Button) findViewById(R.id.nightmode_button);
564        nightmodeButton.setOnClickListener(new View.OnClickListener() {
565            public void onClick(View v) {
566                mDimmed = ! mDimmed;
567                doDim(true);
568            }
569        });
570
571        nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
572            public boolean onLongClick(View v) {
573                saveScreen();
574                return true;
575            }
576        });
577    }
578
579    @Override
580    public void onConfigurationChanged(Configuration newConfig) {
581        super.onConfigurationChanged(newConfig);
582        if (!mScreenSaverMode) {
583            initViews();
584            doDim(false);
585            refreshAll();
586        }
587    }
588
589    @Override
590    protected void onCreate(Bundle icicle) {
591        super.onCreate(icicle);
592
593        mRNG = new Random();
594
595        try {
596            mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
597        } catch (PackageManager.NameNotFoundException e) {
598            // no weather info available
599            Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
600        }
601
602        initViews();
603    }
604
605}
606