DeskClock.java revision 73327b39cf35c8f2f4e5ba1ac30c6fd41a99d10f
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 static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN; 20 21import android.app.Activity; 22import android.app.AlarmManager; 23import android.app.PendingIntent; 24import android.app.UiModeManager; 25import android.content.BroadcastReceiver; 26import android.content.Context; 27import android.content.Intent; 28import android.content.IntentFilter; 29import android.content.pm.PackageManager; 30import android.content.res.Configuration; 31import android.content.res.Resources; 32import android.database.ContentObserver; 33import android.database.Cursor; 34import android.graphics.Rect; 35import android.graphics.drawable.Drawable; 36import android.net.Uri; 37import android.os.BatteryManager; 38import android.os.Bundle; 39import android.os.Handler; 40import android.os.Message; 41import android.provider.MediaStore; 42import android.provider.Settings; 43import android.text.TextUtils; 44import android.text.format.DateFormat; 45import android.util.DisplayMetrics; 46import android.util.Log; 47import android.view.Menu; 48import android.view.MenuInflater; 49import android.view.MenuItem; 50import android.view.MotionEvent; 51import android.view.View; 52import android.view.ViewGroup; 53import android.view.ViewTreeObserver; 54import android.view.Window; 55import android.view.WindowManager; 56import android.view.animation.AnimationUtils; 57import android.widget.AbsoluteLayout; 58import android.widget.ImageButton; 59import android.widget.ImageView; 60import android.widget.TextView; 61 62import java.util.Calendar; 63import java.util.Date; 64import java.util.Random; 65 66/** 67 * DeskClock clock view for desk docks. 68 */ 69public class DeskClock extends Activity { 70 private static final boolean DEBUG = false; 71 72 private static final String LOG_TAG = "DeskClock"; 73 74 // Alarm action for midnight (so we can update the date display). 75 private static final String ACTION_MIDNIGHT = "com.android.deskclock.MIDNIGHT"; 76 77 // Interval between forced polls of the weather widget. 78 private final long QUERY_WEATHER_DELAY = 60 * 60 * 1000; // 1 hr 79 80 // Intent to broadcast for dock settings. 81 private static final String DOCK_SETTINGS_ACTION = "com.android.settings.DOCK_SETTINGS"; 82 83 // Delay before engaging the burn-in protection mode (green-on-black). 84 private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min 85 86 // Repositioning delay in screen saver. 87 public static final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min 88 89 // Color to use for text & graphics in screen saver mode. 90 private final int SCREEN_SAVER_COLOR = 0xFF308030; 91 private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018; 92 93 // Opacity of black layer between clock display and wallpaper. 94 private final float DIM_BEHIND_AMOUNT_NORMAL = 0.4f; 95 private final float DIM_BEHIND_AMOUNT_DIMMED = 0.8f; // higher contrast when display dimmed 96 97 // Internal message IDs. 98 private final int QUERY_WEATHER_DATA_MSG = 0x1000; 99 private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001; 100 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000; 101 private final int SCREEN_SAVER_MOVE_MSG = 0x2001; 102 103 // Weather widget query information. 104 private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget"; 105 private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather"; 106 private static final String WEATHER_CONTENT_PATH = "/weather/current"; 107 private static final String[] WEATHER_CONTENT_COLUMNS = new String[] { 108 "location", 109 "timestamp", 110 "temperature", 111 "highTemperature", 112 "lowTemperature", 113 "iconUrl", 114 "iconResId", 115 "description", 116 }; 117 118 private static final String ACTION_GENIE_REFRESH = "com.google.android.apps.genie.REFRESH"; 119 120 // State variables follow. 121 private DigitalClock mTime; 122 private TextView mDate; 123 124 private TextView mNextAlarm = null; 125 private TextView mBatteryDisplay; 126 127 private TextView mWeatherCurrentTemperature; 128 private TextView mWeatherHighTemperature; 129 private TextView mWeatherLowTemperature; 130 private TextView mWeatherLocation; 131 private ImageView mWeatherIcon; 132 133 private String mWeatherCurrentTemperatureString; 134 private String mWeatherHighTemperatureString; 135 private String mWeatherLowTemperatureString; 136 private String mWeatherLocationString; 137 private Drawable mWeatherIconDrawable; 138 139 private Resources mGenieResources = null; 140 141 private boolean mDimmed = false; 142 private boolean mScreenSaverMode = false; 143 144 private String mDateFormat; 145 146 private int mBatteryLevel = -1; 147 private boolean mPluggedIn = false; 148 149 private boolean mLaunchedFromDock = false; 150 151 private Random mRNG; 152 153 private PendingIntent mMidnightIntent; 154 155 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { 156 @Override 157 public void onReceive(Context context, Intent intent) { 158 final String action = intent.getAction(); 159 if (DEBUG) Log.d(LOG_TAG, "mIntentReceiver.onReceive: action=" + action + ", intent=" + intent); 160 if (Intent.ACTION_DATE_CHANGED.equals(action) || ACTION_MIDNIGHT.equals(action)) { 161 refreshDate(); 162 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { 163 handleBatteryUpdate( 164 intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0), 165 intent.getIntExtra(BatteryManager.EXTRA_STATUS, BATTERY_STATUS_UNKNOWN), 166 intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)); 167 } else if (UiModeManager.ACTION_EXIT_DESK_MODE.equals(action)) { 168 if (mLaunchedFromDock) { 169 // moveTaskToBack(false); 170 finish(); 171 } 172 mLaunchedFromDock = false; 173 } 174 } 175 }; 176 177 private final Handler mHandy = new Handler() { 178 @Override 179 public void handleMessage(Message m) { 180 if (m.what == QUERY_WEATHER_DATA_MSG) { 181 new Thread() { @Override 182 public void run() { queryWeatherData(); } }.start(); 183 scheduleWeatherQueryDelayed(QUERY_WEATHER_DELAY); 184 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) { 185 updateWeatherDisplay(); 186 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) { 187 saveScreen(); 188 } else if (m.what == SCREEN_SAVER_MOVE_MSG) { 189 moveScreenSaver(); 190 } 191 } 192 }; 193 194 private final ContentObserver mContentObserver = new ContentObserver(mHandy) { 195 @Override 196 public void onChange(boolean selfChange) { 197 if (DEBUG) Log.d(LOG_TAG, "content observer notified that weather changed"); 198 refreshWeather(); 199 } 200 }; 201 202 private View mAlarmButton; 203 204 205 private void moveScreenSaver() { 206 moveScreenSaverTo(-1,-1); 207 } 208 private void moveScreenSaverTo(int x, int y) { 209 if (!mScreenSaverMode) return; 210 211 final View saver_view = findViewById(R.id.saver_view); 212 213 DisplayMetrics metrics = new DisplayMetrics(); 214 getWindowManager().getDefaultDisplay().getMetrics(metrics); 215 216 if (x < 0 || y < 0) { 217 int myWidth = saver_view.getMeasuredWidth(); 218 int myHeight = saver_view.getMeasuredHeight(); 219 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth)); 220 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight)); 221 } 222 223 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)", 224 System.currentTimeMillis(), x, y)); 225 226 saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams( 227 ViewGroup.LayoutParams.WRAP_CONTENT, 228 ViewGroup.LayoutParams.WRAP_CONTENT, 229 x, 230 y)); 231 232 // Synchronize our jumping so that it happens exactly on the second. 233 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG, 234 SCREEN_SAVER_MOVE_DELAY + 235 (1000 - (System.currentTimeMillis() % 1000))); 236 } 237 238 private void setWakeLock(boolean hold) { 239 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock"); 240 Window win = getWindow(); 241 WindowManager.LayoutParams winParams = win.getAttributes(); 242 winParams.flags |= (WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 243 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 244 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON 245 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); 246 if (hold) 247 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 248 else 249 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 250 win.setAttributes(winParams); 251 } 252 253 private void scheduleScreenSaver() { 254 if (!getResources().getBoolean(R.bool.config_requiresScreenSaver)) { 255 return; 256 } 257 258 // reschedule screen saver 259 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG); 260 mHandy.sendMessageDelayed( 261 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG), 262 SCREEN_SAVER_TIMEOUT); 263 } 264 265 private void restoreScreen() { 266 if (!mScreenSaverMode) return; 267 if (DEBUG) Log.d(LOG_TAG, "restoreScreen"); 268 mScreenSaverMode = false; 269 270 initViews(); 271 doDim(false); // restores previous dim mode 272 273 scheduleScreenSaver(); 274 275 refreshAll(); 276 } 277 278 // Special screen-saver mode for OLED displays that burn in quickly 279 private void saveScreen() { 280 if (mScreenSaverMode) return; 281 if (DEBUG) Log.d(LOG_TAG, "saveScreen"); 282 283 // quickly stash away the x/y of the current date 284 final View oldTimeDate = findViewById(R.id.time_date); 285 int oldLoc[] = new int[2]; 286 oldTimeDate.getLocationOnScreen(oldLoc); 287 288 mScreenSaverMode = true; 289 Window win = getWindow(); 290 WindowManager.LayoutParams winParams = win.getAttributes(); 291 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 292 win.setAttributes(winParams); 293 294 // give up any internal focus before we switch layouts 295 final View focused = getCurrentFocus(); 296 if (focused != null) focused.clearFocus(); 297 298 setContentView(R.layout.desk_clock_saver); 299 300 mTime = (DigitalClock) findViewById(R.id.time); 301 mDate = (TextView) findViewById(R.id.date); 302 303 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR; 304 305 ((AndroidClockTextView)findViewById(R.id.timeDisplay)).setTextColor(color); 306 ((AndroidClockTextView)findViewById(R.id.am_pm)).setTextColor(color); 307 mDate.setTextColor(color); 308 309 mTime.setSystemUiVisibility(View.STATUS_BAR_HIDDEN); 310 311 mBatteryDisplay = 312 mWeatherCurrentTemperature = 313 mWeatherHighTemperature = 314 mWeatherLowTemperature = 315 mWeatherLocation = null; 316 mWeatherIcon = null; 317 318 refreshDate(); 319 refreshAlarm(); 320 321 moveScreenSaverTo(oldLoc[0], oldLoc[1]); 322 } 323 324 @Override 325 public void onUserInteraction() { 326 if (mScreenSaverMode) 327 restoreScreen(); 328 } 329 330 private boolean supportsWeather() { 331 return (mGenieResources != null); 332 } 333 334 private void scheduleWeatherQueryDelayed(long delay) { 335 // cancel any existing scheduled queries 336 unscheduleWeatherQuery(); 337 338 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now"); 339 340 mHandy.sendEmptyMessageDelayed(QUERY_WEATHER_DATA_MSG, delay); 341 } 342 343 private void unscheduleWeatherQuery() { 344 mHandy.removeMessages(QUERY_WEATHER_DATA_MSG); 345 } 346 347 private void queryWeatherData() { 348 // if we couldn't load the weather widget's resources, we simply 349 // assume it's not present on the device. 350 if (mGenieResources == null) return; 351 352 Uri queryUri = new Uri.Builder() 353 .scheme(android.content.ContentResolver.SCHEME_CONTENT) 354 .authority(WEATHER_CONTENT_AUTHORITY) 355 .path(WEATHER_CONTENT_PATH) 356 .appendPath(new Long(System.currentTimeMillis()).toString()) 357 .build(); 358 359 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri); 360 361 Cursor cur; 362 try { 363 cur = getContentResolver().query( 364 queryUri, 365 WEATHER_CONTENT_COLUMNS, 366 null, 367 null, 368 null); 369 } catch (RuntimeException e) { 370 Log.e(LOG_TAG, "Weather query failed", e); 371 cur = null; 372 } 373 374 if (cur != null && cur.moveToFirst()) { 375 if (DEBUG) { 376 java.lang.StringBuilder sb = 377 new java.lang.StringBuilder("Weather query result: {"); 378 for(int i=0; i<cur.getColumnCount(); i++) { 379 if (i>0) sb.append(", "); 380 sb.append(cur.getColumnName(i)) 381 .append("=") 382 .append(cur.getString(i)); 383 } 384 sb.append("}"); 385 Log.d(LOG_TAG, sb.toString()); 386 } 387 388 int weatherIconResID = cur.getInt(cur.getColumnIndexOrThrow("iconResId")); 389 if (weatherIconResID > 0) { 390 mWeatherIconDrawable = mGenieResources.getDrawable(weatherIconResID); 391 } else { 392 mWeatherIconDrawable = null; 393 } 394 395 mWeatherLocationString = cur.getString( 396 cur.getColumnIndexOrThrow("location")); 397 398 // any of these may be NULL 399 final int colTemp = cur.getColumnIndexOrThrow("temperature"); 400 final int colHigh = cur.getColumnIndexOrThrow("highTemperature"); 401 final int colLow = cur.getColumnIndexOrThrow("lowTemperature"); 402 403 mWeatherCurrentTemperatureString = 404 cur.isNull(colTemp) 405 ? "\u2014" 406 : String.format("%d\u00b0", cur.getInt(colTemp)); 407 mWeatherHighTemperatureString = 408 cur.isNull(colHigh) 409 ? "\u2014" 410 : String.format("%d\u00b0", cur.getInt(colHigh)); 411 mWeatherLowTemperatureString = 412 cur.isNull(colLow) 413 ? "\u2014" 414 : String.format("%d\u00b0", cur.getInt(colLow)); 415 } else { 416 Log.w(LOG_TAG, "No weather information available (cur=" 417 + cur +")"); 418 mWeatherIconDrawable = null; 419 mWeatherLocationString = getString(R.string.weather_fetch_failure); 420 mWeatherCurrentTemperatureString = 421 mWeatherHighTemperatureString = 422 mWeatherLowTemperatureString = ""; 423 } 424 425 if (cur != null) { 426 // clean up cursor 427 cur.close(); 428 } 429 430 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG); 431 } 432 433 private void refreshWeather() { 434 if (supportsWeather()) 435 scheduleWeatherQueryDelayed(0); 436 updateWeatherDisplay(); // in case we have it cached 437 } 438 439 private void updateWeatherDisplay() { 440 if (mWeatherCurrentTemperature == null) return; 441 442 mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString); 443 mWeatherHighTemperature.setText(mWeatherHighTemperatureString); 444 mWeatherLowTemperature.setText(mWeatherLowTemperatureString); 445 mWeatherLocation.setText(mWeatherLocationString); 446 mWeatherIcon.setImageDrawable(mWeatherIconDrawable); 447 } 448 449 // Adapted from KeyguardUpdateMonitor.java 450 private void handleBatteryUpdate(int plugged, int status, int level) { 451 final boolean pluggedIn = (plugged != 0); 452 if (pluggedIn != mPluggedIn) { 453 setWakeLock(pluggedIn); 454 } 455 if (pluggedIn != mPluggedIn || level != mBatteryLevel) { 456 mBatteryLevel = level; 457 mPluggedIn = pluggedIn; 458 refreshBattery(); 459 } 460 } 461 462 private void refreshBattery() { 463 if (mBatteryDisplay == null) return; 464 465 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) { 466 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds( 467 0, 0, android.R.drawable.ic_lock_idle_charging, 0); 468 mBatteryDisplay.setText( 469 getString(R.string.battery_charging_level, mBatteryLevel)); 470 mBatteryDisplay.setVisibility(View.VISIBLE); 471 } else { 472 mBatteryDisplay.setVisibility(View.INVISIBLE); 473 } 474 } 475 476 private void refreshDate() { 477 final Date now = new Date(); 478 if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now); 479 mDate.setText(DateFormat.format(mDateFormat, now)); 480 } 481 482 private void refreshAlarm() { 483 if (mNextAlarm == null) return; 484 485 String nextAlarm = Settings.System.getString(getContentResolver(), 486 Settings.System.NEXT_ALARM_FORMATTED); 487 if (!TextUtils.isEmpty(nextAlarm)) { 488 mNextAlarm.setText(getString(R.string.control_set_alarm_with_existing, nextAlarm)); 489 mNextAlarm.setVisibility(View.VISIBLE); 490 } else if (mAlarmButton != null) { 491 mNextAlarm.setVisibility(View.INVISIBLE); 492 } else { 493 mNextAlarm.setText(R.string.control_set_alarm); 494 mNextAlarm.setVisibility(View.VISIBLE); 495 } 496 } 497 498 private void refreshAll() { 499 refreshDate(); 500 refreshAlarm(); 501 refreshBattery(); 502 refreshWeather(); 503 } 504 505 private void doDim(boolean fade) { 506 View tintView = findViewById(R.id.window_tint); 507 if (tintView == null) return; 508 509 mTime.setSystemUiVisibility(fade ? View.STATUS_BAR_HIDDEN : View.STATUS_BAR_VISIBLE); 510 511 Window win = getWindow(); 512 WindowManager.LayoutParams winParams = win.getAttributes(); 513 514 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); 515 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); 516 517 // dim the wallpaper somewhat (how much is determined below) 518 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND); 519 520 if (mDimmed) { 521 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 522 winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED; 523 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF; 524 525 // show the window tint 526 tintView.startAnimation(AnimationUtils.loadAnimation(this, 527 fade ? R.anim.dim 528 : R.anim.dim_instant)); 529 } else { 530 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN); 531 winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL; 532 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE; 533 534 // hide the window tint 535 tintView.startAnimation(AnimationUtils.loadAnimation(this, 536 fade ? R.anim.undim 537 : R.anim.undim_instant)); 538 } 539 540 win.setAttributes(winParams); 541 } 542 543 @Override 544 public void onNewIntent(Intent newIntent) { 545 super.onNewIntent(newIntent); 546 if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent); 547 548 // update our intent so that we can consult it to determine whether or 549 // not the most recent launch was via a dock event 550 setIntent(newIntent); 551 } 552 553 @Override 554 public void onStart() { 555 super.onStart(); 556 557 IntentFilter filter = new IntentFilter(); 558 filter.addAction(Intent.ACTION_DATE_CHANGED); 559 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 560 filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE); 561 filter.addAction(ACTION_MIDNIGHT); 562 registerReceiver(mIntentReceiver, filter); 563 } 564 565 @Override 566 public void onStop() { 567 super.onStop(); 568 569 unregisterReceiver(mIntentReceiver); 570 } 571 572 @Override 573 public void onResume() { 574 super.onResume(); 575 if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent()); 576 577 // reload the date format in case the user has changed settings 578 // recently 579 mDateFormat = getString(R.string.full_wday_month_day_no_year); 580 581 // Listen for updates to weather data 582 Uri weatherNotificationUri = new Uri.Builder() 583 .scheme(android.content.ContentResolver.SCHEME_CONTENT) 584 .authority(WEATHER_CONTENT_AUTHORITY) 585 .path(WEATHER_CONTENT_PATH) 586 .build(); 587 getContentResolver().registerContentObserver( 588 weatherNotificationUri, true, mContentObserver); 589 590 // Elaborate mechanism to find out when the day rolls over 591 Calendar today = Calendar.getInstance(); 592 today.set(Calendar.HOUR_OF_DAY, 0); 593 today.set(Calendar.MINUTE, 0); 594 today.set(Calendar.SECOND, 0); 595 today.add(Calendar.DATE, 1); 596 long alarmTimeUTC = today.getTimeInMillis(); 597 598 mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0); 599 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 600 am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent); 601 if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at UTC: " 602 + alarmTimeUTC + " (" 603 + (alarmTimeUTC - System.currentTimeMillis()) 604 + " ms from now) repeating every " 605 + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent); 606 607 // If we weren't previously visible but now we are, it's because we're 608 // being started from another activity. So it's OK to un-dim. 609 if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) { 610 mDimmed = false; 611 } 612 613 // Adjust the display to reflect the currently chosen dim mode. 614 doDim(false); 615 616 restoreScreen(); // disable screen saver 617 refreshAll(); // will schedule periodic weather fetch 618 619 setWakeLock(mPluggedIn); 620 621 scheduleScreenSaver(); 622 623 final boolean launchedFromDock 624 = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK); 625 626 mLaunchedFromDock = launchedFromDock; 627 } 628 629 @Override 630 public void onPause() { 631 if (DEBUG) Log.d(LOG_TAG, "onPause"); 632 633 // Turn off the screen saver and cancel any pending timeouts. 634 // (But don't un-dim.) 635 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG); 636 restoreScreen(); 637 638 // Other things we don't want to be doing in the background. 639 // NB: we need to keep our broadcast receiver alive in case the dock 640 // is disconnected while the screen is off 641 getContentResolver().unregisterContentObserver(mContentObserver); 642 643 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 644 am.cancel(mMidnightIntent); 645 unscheduleWeatherQuery(); 646 647 super.onPause(); 648 } 649 650 private void initViews() { 651 // give up any internal focus before we switch layouts 652 final View focused = getCurrentFocus(); 653 if (focused != null) focused.clearFocus(); 654 655 setContentView(R.layout.desk_clock); 656 657 mTime = (DigitalClock) findViewById(R.id.time); 658 mDate = (TextView) findViewById(R.id.date); 659 mBatteryDisplay = (TextView) findViewById(R.id.battery); 660 661 mTime.setSystemUiVisibility(View.STATUS_BAR_VISIBLE); 662 mTime.getRootView().requestFocus(); 663 664 mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature); 665 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature); 666 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature); 667 mWeatherLocation = (TextView) findViewById(R.id.weather_location); 668 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon); 669 670 final View.OnClickListener alarmClickListener = new View.OnClickListener() { 671 public void onClick(View v) { 672 startActivity(new Intent(DeskClock.this, AlarmClock.class)); 673 } 674 }; 675 676 mNextAlarm = (TextView) findViewById(R.id.nextAlarm); 677 mNextAlarm.setOnClickListener(alarmClickListener); 678 679 mAlarmButton = findViewById(R.id.alarm_button); 680 View alarmControl = mAlarmButton != null ? mAlarmButton : findViewById(R.id.nextAlarm); 681 alarmControl.setOnClickListener(alarmClickListener); 682 683 final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button); 684 if (galleryButton != null) { 685 galleryButton.setOnClickListener(new View.OnClickListener() { 686 public void onClick(View v) { 687 try { 688 startActivity(new Intent( 689 Intent.ACTION_VIEW, 690 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI) 691 .putExtra("slideshow", true) 692 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)); 693 } catch (android.content.ActivityNotFoundException e) { 694 Log.e(LOG_TAG, "Couldn't launch image browser", e); 695 } 696 } 697 }); 698 } 699 700 final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button); 701 if (musicButton != null) { 702 musicButton.setOnClickListener(new View.OnClickListener() { 703 public void onClick(View v) { 704 try { 705 startActivity(new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER) 706 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)); 707 708 } catch (android.content.ActivityNotFoundException e) { 709 Log.e(LOG_TAG, "Couldn't launch music browser", e); 710 } 711 } 712 }); 713 } 714 715 final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button); 716 if (homeButton != null) { 717 homeButton.setOnClickListener(new View.OnClickListener() { 718 public void onClick(View v) { 719 startActivity( 720 new Intent(Intent.ACTION_MAIN) 721 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP) 722 .addCategory(Intent.CATEGORY_HOME)); 723 } 724 }); 725 } 726 727 final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button); 728 if (nightmodeButton != null) { 729 nightmodeButton.setOnClickListener(new View.OnClickListener() { 730 public void onClick(View v) { 731 mDimmed = ! mDimmed; 732 doDim(true); 733 } 734 }); 735 736 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() { 737 public boolean onLongClick(View v) { 738 saveScreen(); 739 return true; 740 } 741 }); 742 } 743 744 final View weatherView = findViewById(R.id.weather); 745 if (weatherView != null) { 746 weatherView.setOnClickListener(new View.OnClickListener() { 747 public void onClick(View v) { 748 if (!supportsWeather()) return; 749 750 Intent genieAppQuery = getPackageManager() 751 .getLaunchIntentForPackage(GENIE_PACKAGE_ID) 752 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP); 753 if (genieAppQuery != null) { 754 startActivity(genieAppQuery); 755 } 756 } 757 }); 758 } 759 760 final View tintView = findViewById(R.id.window_tint); 761 tintView.setOnTouchListener(new View.OnTouchListener() { 762 public boolean onTouch(View v, MotionEvent event) { 763 if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) { 764 // We want to un-dim the whole screen on tap. 765 // ...Unless the user is specifically tapping on the dim 766 // widget, in which case let it do the work. 767 Rect r = new Rect(); 768 nightmodeButton.getHitRect(r); 769 int[] gloc = new int[2]; 770 nightmodeButton.getLocationInWindow(gloc); 771 r.offsetTo(gloc[0], gloc[1]); // convert to window coords 772 773 if (!r.contains((int) event.getX(), (int) event.getY())) { 774 mDimmed = false; 775 doDim(true); 776 } 777 } 778 return false; // always pass the click through 779 } 780 }); 781 782 // Tidy up awkward focus behavior: the first view to be focused in 783 // trackball mode should be the alarms button 784 final ViewTreeObserver vto = alarmControl.getViewTreeObserver(); 785 final View alarmView = alarmControl; 786 vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() { 787 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 788 if (oldFocus == null && newFocus == nightmodeButton) { 789 alarmView.requestFocus(); 790 } 791 } 792 }); 793 } 794 795 @Override 796 public void onConfigurationChanged(Configuration newConfig) { 797 super.onConfigurationChanged(newConfig); 798 if (mScreenSaverMode) { 799 moveScreenSaver(); 800 } else { 801 initViews(); 802 doDim(false); 803 refreshAll(); 804 } 805 } 806 807 @Override 808 public boolean onOptionsItemSelected(MenuItem item) { 809 switch (item.getItemId()) { 810 case R.id.menu_item_alarms: 811 startActivity(new Intent(DeskClock.this, AlarmClock.class)); 812 return true; 813 case R.id.menu_item_add_alarm: 814 startActivity(new Intent(this, SetAlarm.class)); 815 return true; 816 case R.id.menu_item_dock_settings: 817 startActivity(new Intent(DOCK_SETTINGS_ACTION)); 818 return true; 819 default: 820 return false; 821 } 822 } 823 824 @Override 825 public boolean onCreateOptionsMenu(Menu menu) { 826 MenuInflater inflater = getMenuInflater(); 827 inflater.inflate(R.menu.desk_clock_menu, menu); 828 return true; 829 } 830 831 @Override 832 public boolean onPrepareOptionsMenu(Menu menu) { 833 // Only show the "Dock settings" menu item if the device supports it. 834 boolean isDockSupported = 835 (getPackageManager().resolveActivity(new Intent(DOCK_SETTINGS_ACTION), 0) != null); 836 menu.findItem(R.id.menu_item_dock_settings).setVisible(isDockSupported); 837 return super.onPrepareOptionsMenu(menu); 838 } 839 840 @Override 841 protected void onCreate(Bundle icicle) { 842 super.onCreate(icicle); 843 844 mRNG = new Random(); 845 846 try { 847 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID); 848 } catch (PackageManager.NameNotFoundException e) { 849 // no weather info available 850 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available."); 851 } 852 853 initViews(); 854 } 855 856} 857