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