DeskClock.java revision 5d1b236620eec1456ca1e9a30085ce2ae27e984d
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() + today.get(Calendar.ZONE_OFFSET); 625 mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0); 626 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 627 am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent); 628 if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at " 629 + alarmTimeUTC + " repeating every " 630 + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent); 631 632 // If we weren't previously visible but now we are, it's because we're 633 // being started from another activity. So it's OK to un-dim. 634 if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) { 635 mDimmed = false; 636 } 637 638 // Adjust the display to reflect the currently chosen dim mode. 639 doDim(false); 640 641 restoreScreen(); // disable screen saver 642 refreshAll(); // will schedule periodic weather fetch 643 644 setWakeLock(mPluggedIn); 645 646 scheduleScreenSaver(); 647 648 final boolean launchedFromDock 649 = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK); 650 651 if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) { 652 // policy: fetch weather if launched via dock connection 653 if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now"); 654 requestWeatherDataFetch(); 655 } 656 657 mLaunchedFromDock = launchedFromDock; 658 } 659 660 @Override 661 public void onPause() { 662 if (DEBUG) Log.d(LOG_TAG, "onPause"); 663 664 // Turn off the screen saver and cancel any pending timeouts. 665 // (But don't un-dim.) 666 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG); 667 restoreScreen(); 668 669 // Other things we don't want to be doing in the background. 670 // NB: we need to keep our broadcast receiver alive in case the dock 671 // is disconnected while the screen is off 672 getContentResolver().unregisterContentObserver(mContentObserver); 673 674 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 675 am.cancel(mMidnightIntent); 676 unscheduleWeatherQuery(); 677 678 super.onPause(); 679 } 680 681 private void initViews() { 682 // give up any internal focus before we switch layouts 683 final View focused = getCurrentFocus(); 684 if (focused != null) focused.clearFocus(); 685 686 setContentView(R.layout.desk_clock); 687 688 mTime = (DigitalClock) findViewById(R.id.time); 689 mDate = (TextView) findViewById(R.id.date); 690 mBatteryDisplay = (TextView) findViewById(R.id.battery); 691 692 mTime.getRootView().requestFocus(); 693 694 mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature); 695 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature); 696 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature); 697 mWeatherLocation = (TextView) findViewById(R.id.weather_location); 698 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon); 699 700 final View.OnClickListener alarmClickListener = new View.OnClickListener() { 701 public void onClick(View v) { 702 startActivity(new Intent(DeskClock.this, AlarmClock.class)); 703 } 704 }; 705 706 mNextAlarm = (TextView) findViewById(R.id.nextAlarm); 707 mNextAlarm.setOnClickListener(alarmClickListener); 708 709 final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button); 710 alarmButton.setOnClickListener(alarmClickListener); 711 712 final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button); 713 galleryButton.setOnClickListener(new View.OnClickListener() { 714 public void onClick(View v) { 715 try { 716 startActivity(new Intent( 717 Intent.ACTION_VIEW, 718 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI) 719 .putExtra("slideshow", true) 720 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)); 721 } catch (android.content.ActivityNotFoundException e) { 722 Log.e(LOG_TAG, "Couldn't launch image browser", e); 723 } 724 } 725 }); 726 727 final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button); 728 musicButton.setOnClickListener(new View.OnClickListener() { 729 public void onClick(View v) { 730 try { 731 startActivity(new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER) 732 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)); 733 734 } catch (android.content.ActivityNotFoundException e) { 735 Log.e(LOG_TAG, "Couldn't launch music browser", e); 736 } 737 } 738 }); 739 740 final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button); 741 homeButton.setOnClickListener(new View.OnClickListener() { 742 public void onClick(View v) { 743 startActivity( 744 new Intent(Intent.ACTION_MAIN) 745 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP) 746 .addCategory(Intent.CATEGORY_HOME)); 747 } 748 }); 749 750 final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button); 751 nightmodeButton.setOnClickListener(new View.OnClickListener() { 752 public void onClick(View v) { 753 mDimmed = ! mDimmed; 754 doDim(true); 755 } 756 }); 757 758 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() { 759 public boolean onLongClick(View v) { 760 saveScreen(); 761 return true; 762 } 763 }); 764 765 final View weatherView = findViewById(R.id.weather); 766 weatherView.setOnClickListener(new View.OnClickListener() { 767 public void onClick(View v) { 768 if (!supportsWeather()) return; 769 770 Intent genieAppQuery = getPackageManager() 771 .getLaunchIntentForPackage(GENIE_PACKAGE_ID) 772 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP); 773 if (genieAppQuery != null) { 774 startActivity(genieAppQuery); 775 } 776 } 777 }); 778 779 final View tintView = findViewById(R.id.window_tint); 780 tintView.setOnTouchListener(new View.OnTouchListener() { 781 public boolean onTouch(View v, MotionEvent event) { 782 if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) { 783 // We want to un-dim the whole screen on tap. 784 // ...Unless the user is specifically tapping on the dim 785 // widget, in which case let it do the work. 786 Rect r = new Rect(); 787 nightmodeButton.getHitRect(r); 788 int[] gloc = new int[2]; 789 nightmodeButton.getLocationInWindow(gloc); 790 r.offsetTo(gloc[0], gloc[1]); // convert to window coords 791 792 if (!r.contains((int) event.getX(), (int) event.getY())) { 793 mDimmed = false; 794 doDim(true); 795 } 796 } 797 return false; // always pass the click through 798 } 799 }); 800 801 // Tidy up awkward focus behavior: the first view to be focused in 802 // trackball mode should be the alarms button 803 final ViewTreeObserver vto = alarmButton.getViewTreeObserver(); 804 vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() { 805 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 806 if (oldFocus == null && newFocus == nightmodeButton) { 807 alarmButton.requestFocus(); 808 } 809 } 810 }); 811 } 812 813 @Override 814 public void onConfigurationChanged(Configuration newConfig) { 815 super.onConfigurationChanged(newConfig); 816 if (mScreenSaverMode) { 817 moveScreenSaver(); 818 } else { 819 initViews(); 820 doDim(false); 821 refreshAll(); 822 } 823 } 824 825 @Override 826 public boolean onOptionsItemSelected(MenuItem item) { 827 switch (item.getItemId()) { 828 case R.id.menu_item_alarms: 829 startActivity(new Intent(DeskClock.this, AlarmClock.class)); 830 return true; 831 case R.id.menu_item_add_alarm: 832 startActivity(new Intent(this, SetAlarm.class)); 833 return true; 834 case R.id.menu_item_dock_settings: 835 startActivity(new Intent(DOCK_SETTINGS_ACTION)); 836 return true; 837 default: 838 return false; 839 } 840 } 841 842 @Override 843 public boolean onCreateOptionsMenu(Menu menu) { 844 MenuInflater inflater = getMenuInflater(); 845 inflater.inflate(R.menu.desk_clock_menu, menu); 846 return true; 847 } 848 849 @Override 850 protected void onCreate(Bundle icicle) { 851 super.onCreate(icicle); 852 853 mRNG = new Random(); 854 855 try { 856 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID); 857 } catch (PackageManager.NameNotFoundException e) { 858 // no weather info available 859 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available."); 860 } 861 862 initViews(); 863 } 864 865} 866