DeskClock.java revision 91522cd49090f40e2e5b96c9b2e310b1adf1218a
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 = true;
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;
137    private boolean mPluggedIn;
138
139    private PowerManager.WakeLock mWakeLock;
140    private int mIdleTimeoutEpoch = 0;
141
142    private boolean mWeatherFetchScheduled = false;
143
144    private Random mRNG;
145
146
147
148    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
149        @Override
150        public void onReceive(Context context, Intent intent) {
151            final String action = intent.getAction();
152            if (Intent.ACTION_DATE_CHANGED.equals(action)) {
153                refreshDate();
154            } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
155                handleBatteryUpdate(
156                    intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
157                    intent.getIntExtra("level", 0));
158            }
159        }
160    };
161
162    private final Handler mHandy = new Handler() {
163        @Override
164        public void handleMessage(Message m) {
165            if (DEBUG) Log.d(LOG_TAG, "handleMessage: " + m.toString());
166
167            if (m.what == FETCH_WEATHER_DATA_MSG) {
168                if (!mWeatherFetchScheduled) return;
169                mWeatherFetchScheduled = false;
170                new Thread() { public void run() { fetchWeatherData(); } }.start();
171                scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
172            } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
173                updateWeatherDisplay();
174            } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
175                if (m.arg1 == mIdleTimeoutEpoch) {
176                    saveScreen();
177                }
178            } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
179                moveScreenSaver();
180            }
181        }
182    };
183    private void moveScreenSaver() {
184        moveScreenSaverTo(-1,-1);
185    }
186    private void moveScreenSaverTo(int x, int y) {
187        if (!mScreenSaverMode) return;
188
189        final View time_date = findViewById(R.id.time_date);
190
191        /*
192        final TranslateAnimation anim = new TranslateAnimation(
193            Animation.RELATIVE_TO_SELF,   0, // fromX
194            Animation.RELATIVE_TO_PARENT, 0.5f, // toX
195            Animation.RELATIVE_TO_SELF,   0, // fromY
196            Animation.RELATIVE_TO_PARENT, 0.5f // toY
197        );
198        anim.setDuration(1000);
199        anim.setInterpolator(new android.view.animation.AccelerateDecelerateInterpolator());
200        anim.setFillEnabled(true);
201        anim.setFillAfter(true);
202        time_date.startAnimation(anim);
203        */
204
205        DisplayMetrics metrics = new DisplayMetrics();
206        getWindowManager().getDefaultDisplay().getMetrics(metrics);
207
208        if (x < 0 || y < 0) {
209            int myWidth = time_date.getMeasuredWidth();
210            int myHeight = time_date.getMeasuredHeight();
211            x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
212            y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
213        }
214
215        time_date.setLayoutParams(new AbsoluteLayout.LayoutParams(
216            ViewGroup.LayoutParams.WRAP_CONTENT,
217            ViewGroup.LayoutParams.WRAP_CONTENT,
218            x,
219            y));
220
221        mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG, SCREEN_SAVER_MOVE_DELAY);
222    }
223
224    private void restoreScreen() {
225        if (!mScreenSaverMode) return;
226        mScreenSaverMode = false;
227        initViews();
228        doDim(false); // restores previous dim mode
229        refreshAll();
230    }
231
232    // Special screen-saver mode for OLED displays that burn in quickly
233    private void saveScreen() {
234        if (mScreenSaverMode) return;
235
236        // quickly stash away the x/y of the current date
237        final View oldTimeDate = findViewById(R.id.time_date);
238        int oldLoc[] = new int[2];
239        oldTimeDate.getLocationOnScreen(oldLoc);
240
241        mScreenSaverMode = true;
242        Window win = getWindow();
243        WindowManager.LayoutParams winParams = win.getAttributes();
244        winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
245        win.setAttributes(winParams);
246
247        setContentView(R.layout.desk_clock_saver);
248
249        mTime = (DigitalClock) findViewById(R.id.time);
250        mDate = (TextView) findViewById(R.id.date);
251
252        final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
253
254        ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
255        ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
256        mDate.setTextColor(color);
257
258        mBatteryDisplay =
259        mNextAlarm =
260        mWeatherHighTemperature =
261        mWeatherLowTemperature =
262        mWeatherLocation = null;
263        mWeatherIcon = null;
264
265        refreshDate();
266
267        moveScreenSaverTo(oldLoc[0], oldLoc[1]);
268    }
269
270    @Override
271    public void onUserInteraction() {
272        if (mScreenSaverMode)
273            restoreScreen();
274    }
275
276    private boolean supportsWeather() {
277        return (mGenieResources != null);
278    }
279
280    private void scheduleWeatherFetchDelayed(long delay) {
281        if (mWeatherFetchScheduled) return;
282
283        if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
284
285        mWeatherFetchScheduled = true;
286
287        mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
288    }
289
290    private void unscheduleWeatherFetch() {
291        mWeatherFetchScheduled = false;
292    }
293
294    private static final boolean sCelsius;
295    static {
296        String cc = Locale.getDefault().getCountry().toLowerCase();
297        sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
298    }
299
300    private static int celsiusToLocal(int tempC) {
301        return sCelsius ? tempC : (int)(tempC * 1.8f + 32);
302    }
303
304    private void fetchWeatherData() {
305        // if we couldn't load the weather widget's resources, we simply
306        // assume it's not present on the device.
307        if (mGenieResources == null) return;
308
309        Uri queryUri = new Uri.Builder()
310            .scheme(android.content.ContentResolver.SCHEME_CONTENT)
311            .authority(WEATHER_CONTENT_AUTHORITY)
312            .path(WEATHER_CONTENT_PATH)
313            .appendPath(new Long(System.currentTimeMillis()).toString())
314            .build();
315
316        if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
317
318        Cursor cur;
319        try {
320            cur = managedQuery(
321                queryUri,
322                WEATHER_CONTENT_COLUMNS,
323                null,
324                null,
325                null);
326        } catch (RuntimeException e) {
327            Log.e(LOG_TAG, "Weather query failed", e);
328            cur = null;
329        }
330
331        if (cur != null && cur.moveToFirst()) {
332            mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
333                cur.getColumnIndexOrThrow("iconResId")));
334            mWeatherHighTemperatureString = String.format("%d\u00b0",
335                celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
336            mWeatherLowTemperatureString = String.format("%d\u00b0",
337                celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
338            mWeatherLocationString = cur.getString(
339                cur.getColumnIndexOrThrow("location"));
340        } else {
341            Log.w(LOG_TAG, "No weather information available (cur="
342                + cur +")");
343            mWeatherIconDrawable = null;
344            mWeatherHighTemperatureString = "";
345            mWeatherLowTemperatureString = "";
346            mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
347        }
348
349        mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
350    }
351
352    private void refreshWeather() {
353        if (supportsWeather())
354            scheduleWeatherFetchDelayed(0);
355        updateWeatherDisplay(); // in case we have it cached
356    }
357
358    private void updateWeatherDisplay() {
359        if (mWeatherHighTemperature == null) return;
360
361        mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
362        mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
363        mWeatherLocation.setText(mWeatherLocationString);
364        mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
365    }
366
367    // Adapted from KeyguardUpdateMonitor.java
368    private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
369        final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
370        if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
371            mBatteryLevel = batteryLevel;
372            mPluggedIn = pluggedIn;
373            refreshBattery();
374
375            if (mPluggedIn) {
376                if (!mWakeLock.isHeld()) mWakeLock.acquire();
377            } else {
378                if (mWakeLock.isHeld()) mWakeLock.release();
379            }
380        }
381    }
382
383    private void refreshBattery() {
384        if (mBatteryDisplay == null) return;
385
386        if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
387            mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
388                0, 0, android.R.drawable.ic_lock_idle_charging, 0);
389            mBatteryDisplay.setText(
390                getString(R.string.battery_charging_level, mBatteryLevel));
391            mBatteryDisplay.setVisibility(View.VISIBLE);
392        } else {
393            mBatteryDisplay.setVisibility(View.INVISIBLE);
394        }
395    }
396
397    private void refreshDate() {
398        mDate.setText(mDateFormat.format(new Date()));
399    }
400
401    private void refreshAlarm() {
402        if (mNextAlarm == null) return;
403
404        String nextAlarm = Settings.System.getString(getContentResolver(),
405                Settings.System.NEXT_ALARM_FORMATTED);
406        if (!TextUtils.isEmpty(nextAlarm)) {
407            mNextAlarm.setText(nextAlarm);
408            //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
409            //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
410            mNextAlarm.setVisibility(View.VISIBLE);
411        } else {
412            mNextAlarm.setVisibility(View.INVISIBLE);
413        }
414    }
415
416    private void refreshAll() {
417        refreshDate();
418        refreshAlarm();
419        refreshBattery();
420        refreshWeather();
421    }
422
423    private void doDim(boolean fade) {
424        View tintView = findViewById(R.id.window_tint);
425        if (tintView == null) return;
426
427        Window win = getWindow();
428        WindowManager.LayoutParams winParams = win.getAttributes();
429
430        // dim the wallpaper somewhat (how much is determined below)
431        winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
432
433        if (mDimmed) {
434            winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
435            winParams.dimAmount = 0.5f; // pump up contrast in dim mode
436
437            // show the window tint
438            tintView.startAnimation(AnimationUtils.loadAnimation(this,
439                fade ? R.anim.dim
440                     : R.anim.dim_instant));
441        } else {
442            winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
443            winParams.dimAmount = 0.2f; // lower contrast in normal mode
444
445            // hide the window tint
446            tintView.startAnimation(AnimationUtils.loadAnimation(this,
447                fade ? R.anim.undim
448                     : R.anim.undim_instant));
449        }
450
451        win.setAttributes(winParams);
452    }
453
454    @Override
455    public void onResume() {
456        super.onResume();
457
458        // reload the date format in case the user has changed settings
459        // recently
460        mDateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
461
462        IntentFilter filter = new IntentFilter();
463        filter.addAction(Intent.ACTION_DATE_CHANGED);
464        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
465        registerReceiver(mIntentReceiver, filter);
466
467        doDim(false);
468        refreshAll();
469        if (mPluggedIn && !mWakeLock.isHeld()) mWakeLock.acquire();
470
471        mIdleTimeoutEpoch++;
472        mHandy.sendMessageDelayed(
473            Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
474            SCREEN_SAVER_TIMEOUT);
475    }
476
477    @Override
478    public void onPause() {
479        super.onPause();
480        unregisterReceiver(mIntentReceiver);
481        unscheduleWeatherFetch();
482        if (mWakeLock.isHeld()) mWakeLock.release();
483    }
484
485
486    private void initViews() {
487        setContentView(R.layout.desk_clock);
488
489        mTime = (DigitalClock) findViewById(R.id.time);
490        mDate = (TextView) findViewById(R.id.date);
491        mBatteryDisplay = (TextView) findViewById(R.id.battery);
492
493        mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
494        mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
495        mWeatherLocation = (TextView) findViewById(R.id.weather_location);
496        mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
497
498        mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
499
500        final Button alarmButton = (Button) findViewById(R.id.alarm_button);
501        alarmButton.setOnClickListener(new View.OnClickListener() {
502            public void onClick(View v) {
503                startActivity(new Intent(DeskClock.this, AlarmClock.class));
504            }
505        });
506
507        final Button galleryButton = (Button) findViewById(R.id.gallery_button);
508        galleryButton.setOnClickListener(new View.OnClickListener() {
509            public void onClick(View v) {
510                try {
511                    startActivity(new Intent(
512                        Intent.ACTION_VIEW,
513                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
514                } catch (android.content.ActivityNotFoundException e) {
515                    Log.e(LOG_TAG, "Couldn't launch image browser", e);
516                }
517            }
518        });
519
520        final Button musicButton = (Button) findViewById(R.id.music_button);
521        musicButton.setOnClickListener(new View.OnClickListener() {
522            public void onClick(View v) {
523                try {
524                    startActivity(new Intent(MUSIC_NOW_PLAYING_ACTIVITY));
525                } catch (android.content.ActivityNotFoundException e) {
526                    Log.e(LOG_TAG, "Couldn't launch music browser", e);
527                }
528            }
529        });
530
531        final Button homeButton = (Button) findViewById(R.id.home_button);
532        homeButton.setOnClickListener(new View.OnClickListener() {
533            public void onClick(View v) {
534                startActivity(
535                    new Intent(Intent.ACTION_MAIN)
536                        .addCategory(Intent.CATEGORY_HOME));
537            }
538        });
539
540        final Button nightmodeButton = (Button) findViewById(R.id.nightmode_button);
541        nightmodeButton.setOnClickListener(new View.OnClickListener() {
542            public void onClick(View v) {
543                mDimmed = ! mDimmed;
544                doDim(true);
545            }
546        });
547
548        nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
549            public boolean onLongClick(View v) {
550                saveScreen();
551                return true;
552            }
553        });
554    }
555
556    @Override
557    public void onConfigurationChanged(Configuration newConfig) {
558        super.onConfigurationChanged(newConfig);
559        if (!mScreenSaverMode) {
560            initViews();
561            doDim(false);
562            refreshAll();
563        }
564    }
565
566    @Override
567    protected void onCreate(Bundle icicle) {
568        super.onCreate(icicle);
569
570        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
571        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
572            "DeskClock");
573        mWakeLock.acquire();
574
575        mRNG = new Random();
576
577        try {
578            mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
579        } catch (PackageManager.NameNotFoundException e) {
580            // no weather info available
581            Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
582        }
583
584        initViews();
585    }
586
587}
588