2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.deskclock;
19 import android.app.Activity;
20 import android.app.AlertDialog;
21 import android.content.BroadcastReceiver;
22 import android.content.Context;
23 import android.content.DialogInterface;
24 import android.content.Intent;
25 import android.content.IntentFilter;
26 import android.content.SharedPreferences;
27 import android.content.pm.PackageManager;
28 import android.content.res.Configuration;
29 import android.content.res.Resources;
30 import android.database.Cursor;
31 import android.graphics.drawable.BitmapDrawable;
32 import android.graphics.drawable.ColorDrawable;
33 import android.graphics.drawable.Drawable;
34 import android.net.Uri;
35 import android.os.Bundle;
36 import android.os.Handler;
37 import android.os.Message;
38 import android.os.SystemClock;
39 import android.os.PowerManager;
40 import android.provider.Settings;
41 import android.text.TextUtils;
42 import android.util.DisplayMetrics;
43 import android.util.Log;
44 import android.view.ContextMenu.ContextMenuInfo;
45 import android.view.ContextMenu;
46 import android.view.LayoutInflater;
47 import android.view.Menu;
48 import android.view.MenuInflater;
49 import android.view.MenuItem;
50 import android.view.View.OnClickListener;
51 import android.view.View.OnCreateContextMenuListener;
52 import android.view.View;
53 import android.view.ViewGroup;
54 import android.view.Window;
55 import android.view.WindowManager;
56 import android.view.animation.Animation;
57 import android.view.animation.AnimationUtils;
58 import android.view.animation.TranslateAnimation;
59 import android.widget.AbsoluteLayout;
60 import android.widget.AdapterView.AdapterContextMenuInfo;
61 import android.widget.AdapterView.OnItemClickListener;
62 import android.widget.AdapterView;
63 import android.widget.Button;
64 import android.widget.CheckBox;
65 import android.widget.ImageButton;
66 import android.widget.ImageView;
67 import android.widget.TextView;
69 import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
70 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
71 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
73 import java.io.IOException;
74 import java.io.InputStream;
75 import java.text.DateFormat;
76 import java.text.SimpleDateFormat;
77 import java.util.Date;
78 import java.util.Locale;
79 import java.util.Random;
82 * DeskClock clock view for desk docks.
84 public class DeskClock extends Activity {
85 private static final boolean DEBUG = false;
87 private static final String LOG_TAG = "DeskClock";
89 // Intent used to start the music player.
90 private static final String MUSIC_NOW_PLAYING = "com.android.music.PLAYBACK_VIEWER";
92 // Interval between polls of the weather widget. Its refresh period is
93 // likely to be much longer (~3h), but we want to pick up any changes
95 private final long FETCH_WEATHER_DELAY = 5 * 60 * 1000; // 5 min
97 // Delay before engaging the burn-in protection mode (green-on-black).
98 private final long SCREEN_SAVER_TIMEOUT = 10 * 60 * 1000; // 10 min
100 // Repositioning delay in screen saver.
101 private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
103 // Color to use for text & graphics in screen saver mode.
104 private final int SCREEN_SAVER_COLOR = 0xFF308030;
105 private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018;
107 // Internal message IDs.
108 private final int FETCH_WEATHER_DATA_MSG = 0x1000;
109 private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
110 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000;
111 private final int SCREEN_SAVER_MOVE_MSG = 0x2001;
113 // Weather widget query information.
114 private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
115 private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
116 private static final String WEATHER_CONTENT_PATH = "/weather/current";
117 private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
128 // State variables follow.
129 private DigitalClock mTime;
130 private TextView mDate;
132 private TextView mNextAlarm = null;
133 private TextView mBatteryDisplay;
135 private TextView mWeatherCurrentTemperature;
136 private TextView mWeatherHighTemperature;
137 private TextView mWeatherLowTemperature;
138 private TextView mWeatherLocation;
139 private ImageView mWeatherIcon;
141 private String mWeatherCurrentTemperatureString;
142 private String mWeatherHighTemperatureString;
143 private String mWeatherLowTemperatureString;
144 private String mWeatherLocationString;
145 private Drawable mWeatherIconDrawable;
147 private Resources mGenieResources = null;
149 private boolean mDimmed = false;
150 private boolean mScreenSaverMode = false;
152 private DateFormat mDateFormat;
154 private int mBatteryLevel = -1;
155 private boolean mPluggedIn = false;
157 private boolean mInDock = false;
159 private int mIdleTimeoutEpoch = 0;
161 private boolean mWeatherFetchScheduled = false;
165 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
167 public void onReceive(Context context, Intent intent) {
168 final String action = intent.getAction();
169 if (Intent.ACTION_DATE_CHANGED.equals(action)) {
171 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
173 intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
174 intent.getIntExtra("level", 0));
179 private final Handler mHandy = new Handler() {
181 public void handleMessage(Message m) {
182 if (m.what == FETCH_WEATHER_DATA_MSG) {
183 if (!mWeatherFetchScheduled) return;
184 mWeatherFetchScheduled = false;
185 new Thread() { public void run() { fetchWeatherData(); } }.start();
186 scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
187 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
188 updateWeatherDisplay();
189 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
190 if (m.arg1 == mIdleTimeoutEpoch) {
193 } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
200 private void moveScreenSaver() {
201 moveScreenSaverTo(-1,-1);
203 private void moveScreenSaverTo(int x, int y) {
204 if (!mScreenSaverMode) return;
206 final View time_date = findViewById(R.id.time_date);
208 DisplayMetrics metrics = new DisplayMetrics();
209 getWindowManager().getDefaultDisplay().getMetrics(metrics);
211 if (x < 0 || y < 0) {
212 int myWidth = time_date.getMeasuredWidth();
213 int myHeight = time_date.getMeasuredHeight();
214 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
215 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
218 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
219 System.currentTimeMillis(), x, y));
221 time_date.setLayoutParams(new AbsoluteLayout.LayoutParams(
222 ViewGroup.LayoutParams.WRAP_CONTENT,
223 ViewGroup.LayoutParams.WRAP_CONTENT,
227 // Synchronize our jumping so that it happens exactly on the second.
228 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
229 SCREEN_SAVER_MOVE_DELAY +
230 (1000 - (System.currentTimeMillis() % 1000)));
233 private void setWakeLock(boolean hold) {
234 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
235 Window win = getWindow();
236 WindowManager.LayoutParams winParams = win.getAttributes();
237 winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
238 winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
239 winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
241 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
243 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
244 win.setAttributes(winParams);
247 private void restoreScreen() {
248 if (!mScreenSaverMode) return;
249 if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
250 mScreenSaverMode = false;
252 doDim(false); // restores previous dim mode
256 // Special screen-saver mode for OLED displays that burn in quickly
257 private void saveScreen() {
258 if (mScreenSaverMode) return;
259 if (DEBUG) Log.d(LOG_TAG, "saveScreen");
261 // quickly stash away the x/y of the current date
262 final View oldTimeDate = findViewById(R.id.time_date);
263 int oldLoc[] = new int[2];
264 oldTimeDate.getLocationOnScreen(oldLoc);
266 mScreenSaverMode = true;
267 Window win = getWindow();
268 WindowManager.LayoutParams winParams = win.getAttributes();
269 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
270 win.setAttributes(winParams);
272 // give up any internal focus before we switch layouts
273 final View focused = getCurrentFocus();
274 if (focused != null) focused.clearFocus();
276 setContentView(R.layout.desk_clock_saver);
278 mTime = (DigitalClock) findViewById(R.id.time);
279 mDate = (TextView) findViewById(R.id.date);
281 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
283 ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
284 ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
285 mDate.setTextColor(color);
289 mWeatherCurrentTemperature =
290 mWeatherHighTemperature =
291 mWeatherLowTemperature =
292 mWeatherLocation = null;
297 moveScreenSaverTo(oldLoc[0], oldLoc[1]);
301 public void onUserInteraction() {
302 if (mScreenSaverMode)
306 private boolean supportsWeather() {
307 return (mGenieResources != null);
310 private void scheduleWeatherFetchDelayed(long delay) {
311 if (mWeatherFetchScheduled) return;
313 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
315 mWeatherFetchScheduled = true;
317 mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
320 private void unscheduleWeatherFetch() {
321 mWeatherFetchScheduled = false;
324 private static final boolean sCelsius;
326 String cc = Locale.getDefault().getCountry().toLowerCase();
327 sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
330 private static int celsiusToLocal(int tempC) {
331 return sCelsius ? tempC : (int) Math.round(tempC * 1.8f + 32);
334 private void fetchWeatherData() {
335 // if we couldn't load the weather widget's resources, we simply
336 // assume it's not present on the device.
337 if (mGenieResources == null) return;
339 Uri queryUri = new Uri.Builder()
340 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
341 .authority(WEATHER_CONTENT_AUTHORITY)
342 .path(WEATHER_CONTENT_PATH)
343 .appendPath(new Long(System.currentTimeMillis()).toString())
346 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
352 WEATHER_CONTENT_COLUMNS,
356 } catch (RuntimeException e) {
357 Log.e(LOG_TAG, "Weather query failed", e);
361 if (cur != null && cur.moveToFirst()) {
363 java.lang.StringBuilder sb =
364 new java.lang.StringBuilder("Weather query result: {");
365 for(int i=0; i<cur.getColumnCount(); i++) {
366 if (i>0) sb.append(", ");
367 sb.append(cur.getColumnName(i))
369 .append(cur.getString(i));
372 Log.d(LOG_TAG, sb.toString());
375 mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
376 cur.getColumnIndexOrThrow("iconResId")));
377 mWeatherCurrentTemperatureString = String.format("%d\u00b0",
378 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
379 mWeatherHighTemperatureString = String.format("%d\u00b0",
380 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
381 mWeatherLowTemperatureString = String.format("%d\u00b0",
382 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
383 mWeatherLocationString = cur.getString(
384 cur.getColumnIndexOrThrow("location"));
386 Log.w(LOG_TAG, "No weather information available (cur="
388 mWeatherIconDrawable = null;
389 mWeatherHighTemperatureString = "";
390 mWeatherLowTemperatureString = "";
391 mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
394 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
397 private void refreshWeather() {
398 if (supportsWeather())
399 scheduleWeatherFetchDelayed(0);
400 updateWeatherDisplay(); // in case we have it cached
403 private void updateWeatherDisplay() {
404 if (mWeatherCurrentTemperature == null) return;
406 mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
407 mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
408 mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
409 mWeatherLocation.setText(mWeatherLocationString);
410 mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
413 // Adapted from KeyguardUpdateMonitor.java
414 private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
415 final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
416 if (pluggedIn != mPluggedIn) {
417 setWakeLock(pluggedIn);
419 if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
420 mBatteryLevel = batteryLevel;
421 mPluggedIn = pluggedIn;
426 private void refreshBattery() {
427 if (mBatteryDisplay == null) return;
429 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
430 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
431 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
432 mBatteryDisplay.setText(
433 getString(R.string.battery_charging_level, mBatteryLevel));
434 mBatteryDisplay.setVisibility(View.VISIBLE);
436 mBatteryDisplay.setVisibility(View.INVISIBLE);
440 private void refreshDate() {
441 mDate.setText(mDateFormat.format(new Date()));
444 private void refreshAlarm() {
445 if (mNextAlarm == null) return;
447 String nextAlarm = Settings.System.getString(getContentResolver(),
448 Settings.System.NEXT_ALARM_FORMATTED);
449 if (!TextUtils.isEmpty(nextAlarm)) {
450 mNextAlarm.setText(nextAlarm);
451 //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
452 // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
453 mNextAlarm.setVisibility(View.VISIBLE);
455 mNextAlarm.setVisibility(View.INVISIBLE);
459 private void refreshAll() {
466 private void doDim(boolean fade) {
467 View tintView = findViewById(R.id.window_tint);
468 if (tintView == null) return;
470 Window win = getWindow();
471 WindowManager.LayoutParams winParams = win.getAttributes();
474 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
475 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
477 // dim the wallpaper somewhat (how much is determined below)
478 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
481 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
482 winParams.dimAmount = 0.67f; // pump up contrast in dim mode
484 // show the window tint
485 tintView.startAnimation(AnimationUtils.loadAnimation(this,
487 : R.anim.dim_instant));
489 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
490 winParams.dimAmount = 0.5f; // lower contrast in normal mode
492 // hide the window tint
493 tintView.startAnimation(AnimationUtils.loadAnimation(this,
495 : R.anim.undim_instant));
498 win.setAttributes(winParams);
502 public void onResume() {
504 if (DEBUG) Log.d(LOG_TAG, "onResume");
506 // reload the date format in case the user has changed settings
508 final SimpleDateFormat dateFormat = (SimpleDateFormat)
509 java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
510 // This is a little clumsy; we want to honor the locale's date format
511 // (rather than simply hardcoding "Weekday, Month Date") but
512 // DateFormat.FULL includes the year (at least, in enUS). So we lop
513 // that bit off if it's there; should have no effect on
514 // locale-specific date strings that look different.
515 mDateFormat = new SimpleDateFormat(dateFormat.toPattern()
516 .replace(", yyyy", "")); // no year
518 IntentFilter filter = new IntentFilter();
519 filter.addAction(Intent.ACTION_DATE_CHANGED);
520 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
521 registerReceiver(mIntentReceiver, filter);
525 refreshAll(); // will schedule periodic weather fetch
527 setWakeLock(mPluggedIn);
530 mHandy.sendMessageDelayed(
531 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
532 SCREEN_SAVER_TIMEOUT);
534 final boolean launchedFromDock
535 = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
537 if (supportsWeather() && launchedFromDock && !mInDock) {
538 if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
540 new Intent("com.google.android.apps.genie.REFRESH")
541 .putExtra("requestWeather", true));
544 mInDock = launchedFromDock;
548 public void onPause() {
549 if (DEBUG) Log.d(LOG_TAG, "onPause");
551 // Turn off the screen saver. (But don't un-dim.)
554 // Other things we don't want to be doing in the background.
555 unregisterReceiver(mIntentReceiver);
556 unscheduleWeatherFetch();
562 public void onStop() {
563 if (DEBUG) Log.d(LOG_TAG, "onStop");
565 // Avoid situations where the user launches Alarm Clock and is
566 // surprised to find it in dim mode (because it was last used in dim
567 // mode, but that last use is long in the past).
573 private void initViews() {
574 // give up any internal focus before we switch layouts
575 final View focused = getCurrentFocus();
576 if (focused != null) focused.clearFocus();
578 setContentView(R.layout.desk_clock);
580 mTime = (DigitalClock) findViewById(R.id.time);
581 mDate = (TextView) findViewById(R.id.date);
582 mBatteryDisplay = (TextView) findViewById(R.id.battery);
584 mTime.getRootView().requestFocus();
586 mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
587 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
588 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
589 mWeatherLocation = (TextView) findViewById(R.id.weather_location);
590 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
592 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
594 final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
595 alarmButton.setOnClickListener(new View.OnClickListener() {
596 public void onClick(View v) {
597 startActivity(new Intent(DeskClock.this, AlarmClock.class));
601 final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
602 galleryButton.setOnClickListener(new View.OnClickListener() {
603 public void onClick(View v) {
605 startActivity(new Intent(
607 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
608 .putExtra("slideshow", true));
609 } catch (android.content.ActivityNotFoundException e) {
610 Log.e(LOG_TAG, "Couldn't launch image browser", e);
615 final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
616 musicButton.setOnClickListener(new View.OnClickListener() {
617 public void onClick(View v) {
619 startActivity(new Intent(MUSIC_NOW_PLAYING));
620 } catch (android.content.ActivityNotFoundException e) {
621 Log.e(LOG_TAG, "Couldn't launch music browser", e);
626 final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
627 homeButton.setOnClickListener(new View.OnClickListener() {
628 public void onClick(View v) {
630 new Intent(Intent.ACTION_MAIN)
631 .addCategory(Intent.CATEGORY_HOME));
635 final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
636 nightmodeButton.setOnClickListener(new View.OnClickListener() {
637 public void onClick(View v) {
643 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
644 public boolean onLongClick(View v) {
650 final View weatherView = findViewById(R.id.weather);
651 weatherView.setOnClickListener(new View.OnClickListener() {
652 public void onClick(View v) {
653 if (!supportsWeather()) return;
655 Intent genieAppQuery = getPackageManager().getLaunchIntentForPackage(GENIE_PACKAGE_ID);
656 if (genieAppQuery != null) {
657 startActivity(genieAppQuery);
664 public void onConfigurationChanged(Configuration newConfig) {
665 super.onConfigurationChanged(newConfig);
666 if (!mScreenSaverMode) {
674 public boolean onOptionsItemSelected(MenuItem item) {
675 if (item.getItemId() == R.id.menu_item_alarms) {
676 startActivity(new Intent(DeskClock.this, AlarmClock.class));
683 public boolean onCreateOptionsMenu(Menu menu) {
684 MenuInflater inflater = getMenuInflater();
685 inflater.inflate(R.menu.desk_clock_menu, menu);
690 protected void onCreate(Bundle icicle) {
691 super.onCreate(icicle);
696 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
697 } catch (PackageManager.NameNotFoundException e) {
698 // no weather info available
699 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");