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