DeskClock.java revision 191b91f419a0ed35104b3436615364b302cfbd67
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 78 // This controls whether or not we will show a battery display when plugged 79 // in. 80 private static final boolean USE_BATTERY_DISPLAY = false; 81 82 // Delay before engaging the burn-in protection mode (green-on-black). 83 private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min 84 85 // Repositioning delay in screen saver. 86 public static final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min 87 88 // Color to use for text & graphics in screen saver mode. 89 private int SCREEN_SAVER_COLOR = 0xFF006688; 90 private int SCREEN_SAVER_COLOR_DIM = 0xFF001634; 91 92 // Opacity of black layer between clock display and wallpaper. 93 private final float DIM_BEHIND_AMOUNT_NORMAL = 0.4f; 94 private final float DIM_BEHIND_AMOUNT_DIMMED = 0.8f; // higher contrast when display dimmed 95 96 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000; 97 private final int SCREEN_SAVER_MOVE_MSG = 0x2001; 98 99 // State variables follow. 100 private DigitalClock mTime; 101 private TextView mDate; 102 103 private TextView mNextAlarm = null; 104 private TextView mBatteryDisplay; 105 106 private boolean mDimmed = false; 107 private boolean mScreenSaverMode = false; 108 109 private String mDateFormat; 110 111 private int mBatteryLevel = -1; 112 private boolean mPluggedIn = false; 113 114 private Random mRNG; 115 116 private PendingIntent mMidnightIntent; 117 118 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { 119 @Override 120 public void onReceive(Context context, Intent intent) { 121 final String action = intent.getAction(); 122 if (DEBUG) Log.d(LOG_TAG, "mIntentReceiver.onReceive: action=" + action + ", intent=" + intent); 123 if (Intent.ACTION_DATE_CHANGED.equals(action) || ACTION_MIDNIGHT.equals(action)) { 124 refreshDate(); 125 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { 126 handleBatteryUpdate( 127 intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0), 128 intent.getIntExtra(BatteryManager.EXTRA_STATUS, BATTERY_STATUS_UNKNOWN), 129 intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)); 130 } 131 } 132 }; 133 134 private final Handler mHandy = new Handler() { 135 @Override 136 public void handleMessage(Message m) { 137 if (m.what == SCREEN_SAVER_TIMEOUT_MSG) { 138 saveScreen(); 139 } else if (m.what == SCREEN_SAVER_MOVE_MSG) { 140 moveScreenSaver(); 141 } 142 } 143 }; 144 145 private View mAlarmButton; 146 147 private void moveScreenSaver() { 148 moveScreenSaverTo(-1,-1); 149 } 150 private void moveScreenSaverTo(int x, int y) { 151 if (!mScreenSaverMode) return; 152 153 final View saver_view = findViewById(R.id.saver_view); 154 155 DisplayMetrics metrics = new DisplayMetrics(); 156 getWindowManager().getDefaultDisplay().getMetrics(metrics); 157 158 if (x < 0 || y < 0) { 159 int myWidth = saver_view.getMeasuredWidth(); 160 int myHeight = saver_view.getMeasuredHeight(); 161 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth)); 162 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight)); 163 } 164 165 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)", 166 System.currentTimeMillis(), x, y)); 167 168 saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams( 169 ViewGroup.LayoutParams.WRAP_CONTENT, 170 ViewGroup.LayoutParams.WRAP_CONTENT, 171 x, 172 y)); 173 174 // Synchronize our jumping so that it happens exactly on the second. 175 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG, 176 SCREEN_SAVER_MOVE_DELAY + 177 (1000 - (System.currentTimeMillis() % 1000))); 178 } 179 180 private void setWakeLock(boolean hold) { 181 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock"); 182 Window win = getWindow(); 183 WindowManager.LayoutParams winParams = win.getAttributes(); 184 winParams.flags |= (WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 185 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 186 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON 187 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); 188 if (hold) 189 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 190 else 191 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 192 win.setAttributes(winParams); 193 } 194 195 private void scheduleScreenSaver() { 196 if (!getResources().getBoolean(R.bool.config_requiresScreenSaver)) { 197 return; 198 } 199 200 // reschedule screen saver 201 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG); 202 mHandy.sendMessageDelayed( 203 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG), 204 SCREEN_SAVER_TIMEOUT); 205 } 206 207 private void restoreScreen() { 208 if (!mScreenSaverMode) return; 209 if (DEBUG) Log.d(LOG_TAG, "restoreScreen"); 210 mScreenSaverMode = false; 211 212 initViews(); 213 doDim(false); // restores previous dim mode 214 215 scheduleScreenSaver(); 216 217 refreshAll(); 218 } 219 220 // Special screen-saver mode for OLED displays that burn in quickly 221 private void saveScreen() { 222 if (mScreenSaverMode) return; 223 if (DEBUG) Log.d(LOG_TAG, "saveScreen"); 224 225 // quickly stash away the x/y of the current date 226 final View oldTimeDate = findViewById(R.id.time_date); 227 int oldLoc[] = new int[2]; 228 oldTimeDate.getLocationOnScreen(oldLoc); 229 230 mScreenSaverMode = true; 231 Window win = getWindow(); 232 WindowManager.LayoutParams winParams = win.getAttributes(); 233 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 234 win.setAttributes(winParams); 235 236 // give up any internal focus before we switch layouts 237 final View focused = getCurrentFocus(); 238 if (focused != null) focused.clearFocus(); 239 240 setContentView(R.layout.desk_clock_saver); 241 242 mTime = (DigitalClock) findViewById(R.id.time); 243 mDate = (TextView) findViewById(R.id.date); 244 245 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR; 246 247 ((AndroidClockTextView)findViewById(R.id.timeDisplay)).setTextColor(color); 248 ((AndroidClockTextView)findViewById(R.id.am_pm)).setTextColor(color); 249 mDate.setTextColor(color); 250 251 mTime.setSystemUiVisibility(View.STATUS_BAR_HIDDEN); 252 253 mBatteryDisplay = null; 254 255 refreshDate(); 256 refreshAlarm(); 257 258 moveScreenSaverTo(oldLoc[0], oldLoc[1]); 259 } 260 261 @Override 262 public void onUserInteraction() { 263 if (mScreenSaverMode) 264 restoreScreen(); 265 } 266 267 // Adapted from KeyguardUpdateMonitor.java 268 private void handleBatteryUpdate(int plugged, int status, int level) { 269 final boolean pluggedIn = (plugged != 0); 270 if (pluggedIn != mPluggedIn) { 271 setWakeLock(pluggedIn); 272 } 273 if (pluggedIn != mPluggedIn || level != mBatteryLevel) { 274 mBatteryLevel = level; 275 mPluggedIn = pluggedIn; 276 refreshBattery(); 277 } 278 } 279 280 private void refreshBattery() { 281 // UX wants the battery level removed. This makes it not visible but 282 // allows it to be easily turned back on if they change their mind. 283 if (!USE_BATTERY_DISPLAY) 284 return; 285 if (mBatteryDisplay == null) return; 286 287 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) { 288 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds( 289 0, 0, android.R.drawable.ic_lock_idle_charging, 0); 290 mBatteryDisplay.setText( 291 getString(R.string.battery_charging_level, mBatteryLevel)); 292 mBatteryDisplay.setVisibility(View.VISIBLE); 293 } else { 294 mBatteryDisplay.setVisibility(View.INVISIBLE); 295 } 296 } 297 298 private void refreshDate() { 299 final Date now = new Date(); 300 if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now); 301 mDate.setText(DateFormat.format(mDateFormat, now)); 302 } 303 304 private void refreshAlarm() { 305 if (mNextAlarm == null) return; 306 307 String nextAlarm = Settings.System.getString(getContentResolver(), 308 Settings.System.NEXT_ALARM_FORMATTED); 309 if (!TextUtils.isEmpty(nextAlarm)) { 310 mNextAlarm.setText(getString(R.string.control_set_alarm_with_existing, nextAlarm)); 311 mNextAlarm.setVisibility(View.VISIBLE); 312 } else if (mAlarmButton != null) { 313 mNextAlarm.setVisibility(View.INVISIBLE); 314 } else { 315 mNextAlarm.setText(R.string.control_set_alarm); 316 mNextAlarm.setVisibility(View.VISIBLE); 317 } 318 } 319 320 private void refreshAll() { 321 refreshDate(); 322 refreshAlarm(); 323 refreshBattery(); 324 } 325 326 private void doDim(boolean fade) { 327 View tintView = findViewById(R.id.window_tint); 328 if (tintView == null) return; 329 330 mTime.setSystemUiVisibility(mDimmed ? View.SYSTEM_UI_FLAG_LOW_PROFILE 331 : View.SYSTEM_UI_FLAG_VISIBLE); 332 333 Window win = getWindow(); 334 WindowManager.LayoutParams winParams = win.getAttributes(); 335 336 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); 337 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); 338 339 // dim the wallpaper somewhat (how much is determined below) 340 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND); 341 342 if (mDimmed) { 343 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 344 winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED; 345 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF; 346 347 // show the window tint 348 tintView.startAnimation(AnimationUtils.loadAnimation(this, 349 fade ? R.anim.dim 350 : R.anim.dim_instant)); 351 } else { 352 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN); 353 winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL; 354 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE; 355 356 // hide the window tint 357 tintView.startAnimation(AnimationUtils.loadAnimation(this, 358 fade ? R.anim.undim 359 : R.anim.undim_instant)); 360 } 361 362 win.setAttributes(winParams); 363 } 364 365 @Override 366 public void onNewIntent(Intent newIntent) { 367 super.onNewIntent(newIntent); 368 if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent); 369 370 // update our intent so that we can consult it to determine whether or 371 // not the most recent launch was via a dock event 372 setIntent(newIntent); 373 } 374 375 @Override 376 public void onStart() { 377 super.onStart(); 378 379 SCREEN_SAVER_COLOR = getResources().getColor(R.color.screen_saver_color); 380 SCREEN_SAVER_COLOR_DIM = getResources().getColor(R.color.screen_saver_dim_color); 381 382 IntentFilter filter = new IntentFilter(); 383 filter.addAction(Intent.ACTION_DATE_CHANGED); 384 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 385 filter.addAction(ACTION_MIDNIGHT); 386 registerReceiver(mIntentReceiver, filter); 387 } 388 389 @Override 390 public void onStop() { 391 super.onStop(); 392 393 unregisterReceiver(mIntentReceiver); 394 } 395 396 @Override 397 public void onResume() { 398 super.onResume(); 399 if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent()); 400 401 // reload the date format in case the user has changed settings 402 // recently 403 mDateFormat = getString(R.string.full_wday_month_day_no_year); 404 405 // Elaborate mechanism to find out when the day rolls over 406 Calendar today = Calendar.getInstance(); 407 today.set(Calendar.HOUR_OF_DAY, 0); 408 today.set(Calendar.MINUTE, 0); 409 today.set(Calendar.SECOND, 0); 410 today.add(Calendar.DATE, 1); 411 long alarmTimeUTC = today.getTimeInMillis(); 412 413 mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0); 414 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 415 am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent); 416 if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at UTC: " 417 + alarmTimeUTC + " (" 418 + (alarmTimeUTC - System.currentTimeMillis()) 419 + " ms from now) repeating every " 420 + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent); 421 422 // If we weren't previously visible but now we are, it's because we're 423 // being started from another activity. So it's OK to un-dim. 424 if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) { 425 mDimmed = false; 426 } 427 428 // Adjust the display to reflect the currently chosen dim mode. 429 doDim(false); 430 431 restoreScreen(); // disable screen saver 432 refreshAll(); // will schedule periodic weather fetch 433 434 setWakeLock(mPluggedIn); 435 436 scheduleScreenSaver(); 437 } 438 439 @Override 440 public void onPause() { 441 if (DEBUG) Log.d(LOG_TAG, "onPause"); 442 443 // Turn off the screen saver and cancel any pending timeouts. 444 // (But don't un-dim.) 445 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG); 446 restoreScreen(); 447 448 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 449 am.cancel(mMidnightIntent); 450 451 super.onPause(); 452 } 453 454 private void initViews() { 455 // give up any internal focus before we switch layouts 456 final View focused = getCurrentFocus(); 457 if (focused != null) focused.clearFocus(); 458 459 setContentView(R.layout.desk_clock); 460 461 mTime = (DigitalClock) findViewById(R.id.time); 462 mDate = (TextView) findViewById(R.id.date); 463 mBatteryDisplay = (TextView) findViewById(R.id.battery); 464 465 mTime.setSystemUiVisibility(View.STATUS_BAR_VISIBLE); 466 mTime.getRootView().requestFocus(); 467 468 final View.OnClickListener alarmClickListener = new View.OnClickListener() { 469 @Override 470 public void onClick(View v) { 471 mDimmed = false; 472 doDim(true); 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 522 initViews(); 523 } 524} 525