DeskClock.java revision 7e77977037b89c775faa0a480c8ce70eb820dc20
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.deskclock; 18 19import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN; 20 21import android.app.Activity; 22import android.app.AlarmManager; 23import android.app.PendingIntent; 24import android.app.UiModeManager; 25import android.content.BroadcastReceiver; 26import android.content.Context; 27import android.content.Intent; 28import android.content.IntentFilter; 29import android.content.pm.PackageManager; 30import android.content.res.Configuration; 31import android.content.res.Resources; 32import android.database.ContentObserver; 33import android.database.Cursor; 34import android.graphics.Rect; 35import android.graphics.drawable.Drawable; 36import android.net.Uri; 37import android.os.BatteryManager; 38import android.os.Bundle; 39import android.os.Handler; 40import android.os.Message; 41import android.provider.MediaStore; 42import android.provider.Settings; 43import android.text.TextUtils; 44import android.text.format.DateFormat; 45import android.util.DisplayMetrics; 46import android.util.Log; 47import android.view.GestureDetector; 48import android.view.Menu; 49import android.view.MenuInflater; 50import android.view.MenuItem; 51import android.view.MotionEvent; 52import android.view.View; 53import android.view.ViewGroup; 54import android.view.ViewTreeObserver; 55import android.view.Window; 56import android.view.WindowManager; 57import android.view.animation.AnimationUtils; 58import android.widget.AbsoluteLayout; 59import android.widget.ImageButton; 60import android.widget.ImageView; 61import android.widget.TextView; 62 63import java.util.Calendar; 64import java.util.Date; 65import java.util.Random; 66 67/** 68 * A clock. On your desk. 69 */ 70public class DeskClock extends Activity { 71 private static final boolean DEBUG = false; 72 73 private static final String LOG_TAG = "DeskClock"; 74 75 // Alarm action for midnight (so we can update the date display). 76 private static final String ACTION_MIDNIGHT = "com.android.deskclock.MIDNIGHT"; 77 private static final String KEY_DIMMED = "dimmed"; 78 private static final String KEY_SCREEN_SAVER = "screen_saver"; 79 80 // This controls whether or not we will show a battery display when plugged 81 // in. 82 private static final boolean USE_BATTERY_DISPLAY = false; 83 84 // Delay before engaging the burn-in protection mode (green-on-black). 85 private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min 86 87 // Repositioning delay in screen saver. 88 public static final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min 89 90 // Color to use for text & graphics in screen saver mode. 91 private int SCREEN_SAVER_COLOR = 0xFF006688; 92 private int SCREEN_SAVER_COLOR_DIM = 0xFF001634; 93 94 // Opacity of black layer between clock display and wallpaper. 95 private final float DIM_BEHIND_AMOUNT_NORMAL = 0.4f; 96 private final float DIM_BEHIND_AMOUNT_DIMMED = 0.8f; // higher contrast when display dimmed 97 98 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000; 99 private final int SCREEN_SAVER_MOVE_MSG = 0x2001; 100 101 // State variables follow. 102 private DigitalClock mTime; 103 private TextView mDate; 104 105 private TextView mNextAlarm = null; 106 private TextView mBatteryDisplay; 107 108 private boolean mDimmed = false; 109 private boolean mScreenSaverMode = false; 110 111 private String mDateFormat; 112 113 private int mBatteryLevel = -1; 114 private boolean mPluggedIn = false; 115 116 private Random mRNG; 117 118 private PendingIntent mMidnightIntent; 119 120 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { 121 @Override 122 public void onReceive(Context context, Intent intent) { 123 final String action = intent.getAction(); 124 if (DEBUG) Log.d(LOG_TAG, "mIntentReceiver.onReceive: action=" + action + ", intent=" + intent); 125 if (Intent.ACTION_DATE_CHANGED.equals(action) || ACTION_MIDNIGHT.equals(action)) { 126 refreshDate(); 127 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { 128 handleBatteryUpdate( 129 intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0), 130 intent.getIntExtra(BatteryManager.EXTRA_STATUS, BATTERY_STATUS_UNKNOWN), 131 intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)); 132 } 133 } 134 }; 135 136 private final Handler mHandy = new Handler() { 137 @Override 138 public void handleMessage(Message m) { 139 if (m.what == SCREEN_SAVER_TIMEOUT_MSG) { 140 saveScreen(); 141 } else if (m.what == SCREEN_SAVER_MOVE_MSG) { 142 moveScreenSaver(); 143 } 144 } 145 }; 146 147 private View mAlarmButton; 148 149 private void moveScreenSaver() { 150 moveScreenSaverTo(-1,-1); 151 } 152 private void moveScreenSaverTo(int x, int y) { 153 if (!mScreenSaverMode) return; 154 155 final View saver_view = findViewById(R.id.saver_view); 156 157 DisplayMetrics metrics = new DisplayMetrics(); 158 getWindowManager().getDefaultDisplay().getMetrics(metrics); 159 160 if (x < 0 || y < 0) { 161 int myWidth = saver_view.getMeasuredWidth(); 162 int myHeight = saver_view.getMeasuredHeight(); 163 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth)); 164 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight)); 165 } 166 167 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)", 168 System.currentTimeMillis(), x, y)); 169 170 saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams( 171 ViewGroup.LayoutParams.WRAP_CONTENT, 172 ViewGroup.LayoutParams.WRAP_CONTENT, 173 x, 174 y)); 175 176 // Synchronize our jumping so that it happens exactly on the second. 177 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG, 178 SCREEN_SAVER_MOVE_DELAY + 179 (1000 - (System.currentTimeMillis() % 1000))); 180 } 181 182 private void setWakeLock(boolean hold) { 183 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock"); 184 Window win = getWindow(); 185 WindowManager.LayoutParams winParams = win.getAttributes(); 186 winParams.flags |= (WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 187 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 188 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON 189 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); 190 if (hold) 191 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 192 else 193 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 194 win.setAttributes(winParams); 195 } 196 197 private void scheduleScreenSaver() { 198 if (!getResources().getBoolean(R.bool.config_requiresScreenSaver)) { 199 return; 200 } 201 202 // reschedule screen saver 203 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG); 204 mHandy.sendMessageDelayed( 205 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG), 206 SCREEN_SAVER_TIMEOUT); 207 } 208 209 private void restoreScreen() { 210 if (!mScreenSaverMode) return; 211 if (DEBUG) Log.d(LOG_TAG, "restoreScreen"); 212 mScreenSaverMode = false; 213 214 initViews(); 215 doDim(false); // restores previous dim mode 216 217 scheduleScreenSaver(); 218 219 refreshAll(); 220 } 221 222 // Special screen-saver mode for OLED displays that burn in quickly 223 private void saveScreen() { 224 if (mScreenSaverMode) return; 225 if (DEBUG) Log.d(LOG_TAG, "saveScreen"); 226 227 // quickly stash away the x/y of the current date 228 final View oldTimeDate = findViewById(R.id.time_date); 229 int oldLoc[] = new int[2]; 230 oldTimeDate.getLocationOnScreen(oldLoc); 231 232 mScreenSaverMode = true; 233 Window win = getWindow(); 234 WindowManager.LayoutParams winParams = win.getAttributes(); 235 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 236 win.setAttributes(winParams); 237 238 // give up any internal focus before we switch layouts 239 final View focused = getCurrentFocus(); 240 if (focused != null) focused.clearFocus(); 241 242 setContentView(R.layout.desk_clock_saver); 243 244 mTime = (DigitalClock) findViewById(R.id.time); 245 mDate = (TextView) findViewById(R.id.date); 246 247 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR; 248 249 ((AndroidClockTextView)findViewById(R.id.timeDisplay)).setTextColor(color); 250 ((AndroidClockTextView)findViewById(R.id.am_pm)).setTextColor(color); 251 mDate.setTextColor(color); 252 253 mTime.setSystemUiVisibility(View.STATUS_BAR_HIDDEN); 254 255 mBatteryDisplay = null; 256 257 refreshDate(); 258 refreshAlarm(); 259 260 moveScreenSaverTo(oldLoc[0], oldLoc[1]); 261 } 262 263 @Override 264 public void onUserInteraction() { 265 if (mScreenSaverMode) 266 restoreScreen(); 267 } 268 269 // Adapted from KeyguardUpdateMonitor.java 270 private void handleBatteryUpdate(int plugged, int status, int level) { 271 final boolean pluggedIn = (plugged != 0); 272 if (pluggedIn != mPluggedIn) { 273 setWakeLock(pluggedIn); 274 } 275 if (pluggedIn != mPluggedIn || level != mBatteryLevel) { 276 mBatteryLevel = level; 277 mPluggedIn = pluggedIn; 278 refreshBattery(); 279 } 280 } 281 282 private void refreshBattery() { 283 // UX wants the battery level removed. This makes it not visible but 284 // allows it to be easily turned back on if they change their mind. 285 if (!USE_BATTERY_DISPLAY) 286 return; 287 if (mBatteryDisplay == null) return; 288 289 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) { 290 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds( 291 0, 0, android.R.drawable.ic_lock_idle_charging, 0); 292 mBatteryDisplay.setText( 293 getString(R.string.battery_charging_level, mBatteryLevel)); 294 mBatteryDisplay.setVisibility(View.VISIBLE); 295 } else { 296 mBatteryDisplay.setVisibility(View.INVISIBLE); 297 } 298 } 299 300 private void refreshDate() { 301 final Date now = new Date(); 302 if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now); 303 mDate.setText(DateFormat.format(mDateFormat, now)); 304 } 305 306 private void refreshAlarm() { 307 if (mNextAlarm == null) return; 308 309 String nextAlarm = Settings.System.getString(getContentResolver(), 310 Settings.System.NEXT_ALARM_FORMATTED); 311 if (!TextUtils.isEmpty(nextAlarm)) { 312 mNextAlarm.setText(getString(R.string.control_set_alarm_with_existing, nextAlarm)); 313 mNextAlarm.setVisibility(View.VISIBLE); 314 } else if (mAlarmButton != null) { 315 mNextAlarm.setVisibility(View.INVISIBLE); 316 } else { 317 mNextAlarm.setText(R.string.control_set_alarm); 318 mNextAlarm.setVisibility(View.VISIBLE); 319 } 320 } 321 322 private void refreshAll() { 323 refreshDate(); 324 refreshAlarm(); 325 refreshBattery(); 326 } 327 328 private void doDim(boolean fade) { 329 View tintView = findViewById(R.id.window_tint); 330 if (tintView == null) return; 331 332 mTime.setSystemUiVisibility(mDimmed ? View.SYSTEM_UI_FLAG_LOW_PROFILE 333 : View.SYSTEM_UI_FLAG_VISIBLE); 334 335 Window win = getWindow(); 336 WindowManager.LayoutParams winParams = win.getAttributes(); 337 338 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); 339 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); 340 341 // dim the wallpaper somewhat (how much is determined below) 342 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND); 343 344 if (mDimmed) { 345 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 346 winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED; 347 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF; 348 349 // show the window tint 350 tintView.startAnimation(AnimationUtils.loadAnimation(this, 351 fade ? R.anim.dim 352 : R.anim.dim_instant)); 353 } else { 354 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN); 355 winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL; 356 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE; 357 358 // hide the window tint 359 tintView.startAnimation(AnimationUtils.loadAnimation(this, 360 fade ? R.anim.undim 361 : R.anim.undim_instant)); 362 } 363 364 win.setAttributes(winParams); 365 } 366 367 @Override 368 public void onNewIntent(Intent newIntent) { 369 super.onNewIntent(newIntent); 370 if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent); 371 372 // update our intent so that we can consult it to determine whether or 373 // not the most recent launch was via a dock event 374 setIntent(newIntent); 375 } 376 377 @Override 378 public void onStart() { 379 super.onStart(); 380 381 SCREEN_SAVER_COLOR = getResources().getColor(R.color.screen_saver_color); 382 SCREEN_SAVER_COLOR_DIM = getResources().getColor(R.color.screen_saver_dim_color); 383 384 IntentFilter filter = new IntentFilter(); 385 filter.addAction(Intent.ACTION_DATE_CHANGED); 386 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 387 filter.addAction(ACTION_MIDNIGHT); 388 registerReceiver(mIntentReceiver, filter); 389 } 390 391 @Override 392 public void onStop() { 393 super.onStop(); 394 395 unregisterReceiver(mIntentReceiver); 396 } 397 398 @Override 399 public void onResume() { 400 super.onResume(); 401 if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent()); 402 403 // reload the date format in case the user has changed settings 404 // recently 405 mDateFormat = getString(R.string.full_wday_month_day_no_year); 406 407 // Elaborate mechanism to find out when the day rolls over 408 Calendar today = Calendar.getInstance(); 409 today.set(Calendar.HOUR_OF_DAY, 0); 410 today.set(Calendar.MINUTE, 0); 411 today.set(Calendar.SECOND, 0); 412 today.add(Calendar.DATE, 1); 413 long alarmTimeUTC = today.getTimeInMillis(); 414 415 mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0); 416 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 417 am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent); 418 if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at UTC: " 419 + alarmTimeUTC + " (" 420 + (alarmTimeUTC - System.currentTimeMillis()) 421 + " ms from now) repeating every " 422 + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent); 423 424 // Adjust the display to reflect the currently chosen dim mode. 425 doDim(false); 426 427 if (!mScreenSaverMode) { 428 restoreScreen(); // disable screen saver 429 } else { 430 // we have to set it to false because savescreen returns early if 431 // it's true 432 mScreenSaverMode = false; 433 saveScreen(); 434 } 435 refreshAll(); // will schedule periodic weather fetch 436 437 setWakeLock(mPluggedIn); 438 439 scheduleScreenSaver(); 440 } 441 442 @Override 443 public void onPause() { 444 if (DEBUG) Log.d(LOG_TAG, "onPause"); 445 446 // Turn off the screen saver and cancel any pending timeouts. 447 // (But don't un-dim.) 448 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG); 449 450 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 451 am.cancel(mMidnightIntent); 452 453 super.onPause(); 454 } 455 456 private void initViews() { 457 // give up any internal focus before we switch layouts 458 final View focused = getCurrentFocus(); 459 if (focused != null) focused.clearFocus(); 460 461 setContentView(R.layout.desk_clock); 462 463 mTime = (DigitalClock) findViewById(R.id.time); 464 mDate = (TextView) findViewById(R.id.date); 465 mBatteryDisplay = (TextView) findViewById(R.id.battery); 466 467 mTime.setSystemUiVisibility(View.STATUS_BAR_VISIBLE); 468 mTime.getRootView().requestFocus(); 469 470 final View.OnClickListener alarmClickListener = new View.OnClickListener() { 471 @Override 472 public void onClick(View v) { 473 startActivity(new Intent(DeskClock.this, AlarmClock.class)); 474 } 475 }; 476 477 mNextAlarm = (TextView) findViewById(R.id.nextAlarm); 478 mNextAlarm.setOnClickListener(alarmClickListener); 479 480 mAlarmButton = findViewById(R.id.alarm_button); 481 View alarmControl = mAlarmButton != null ? mAlarmButton : findViewById(R.id.nextAlarm); 482 alarmControl.setOnClickListener(alarmClickListener); 483 484 View touchView = findViewById(R.id.window_touch); 485 touchView.setOnClickListener(new View.OnClickListener() { 486 @Override 487 public void onClick(View v) { 488 // If the screen saver is on let onUserInteraction handle it 489 if (!mScreenSaverMode) { 490 mDimmed = !mDimmed; 491 doDim(true); 492 } 493 } 494 }); 495 touchView.setOnLongClickListener(new View.OnLongClickListener() { 496 @Override 497 public boolean onLongClick(View v) { 498 saveScreen(); 499 return true; 500 } 501 }); 502 } 503 504 @Override 505 public void onConfigurationChanged(Configuration newConfig) { 506 super.onConfigurationChanged(newConfig); 507 if (mScreenSaverMode) { 508 moveScreenSaver(); 509 } else { 510 initViews(); 511 doDim(false); 512 refreshAll(); 513 } 514 } 515 516 @Override 517 protected void onCreate(Bundle icicle) { 518 super.onCreate(icicle); 519 520 mRNG = new Random(); 521 if (icicle != null) { 522 mDimmed = icicle.getBoolean(KEY_DIMMED, false); 523 mScreenSaverMode = icicle.getBoolean(KEY_SCREEN_SAVER, false); 524 } 525 526 initViews(); 527 } 528 529 @Override 530 protected void onSaveInstanceState(Bundle outState) { 531 outState.putBoolean(KEY_DIMMED, mDimmed); 532 outState.putBoolean(KEY_SCREEN_SAVER, mScreenSaverMode); 533 } 534} 535