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