2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.deskclock;
19 import android.app.Activity;
20 import android.app.AlertDialog;
21 import android.content.BroadcastReceiver;
22 import android.content.Context;
23 import android.content.DialogInterface;
24 import android.content.Intent;
25 import android.content.IntentFilter;
26 import android.content.SharedPreferences;
27 import android.content.pm.PackageManager;
28 import android.content.res.Configuration;
29 import android.content.res.Resources;
30 import android.database.Cursor;
31 import android.graphics.drawable.BitmapDrawable;
32 import android.graphics.drawable.ColorDrawable;
33 import android.graphics.drawable.Drawable;
34 import android.net.Uri;
35 import android.os.Bundle;
36 import android.os.Handler;
37 import android.os.Message;
38 import android.os.SystemClock;
39 import android.os.PowerManager;
40 import android.provider.Settings;
41 import android.text.TextUtils;
42 import android.util.DisplayMetrics;
43 import android.util.Log;
44 import android.view.ContextMenu.ContextMenuInfo;
45 import android.view.ContextMenu;
46 import android.view.LayoutInflater;
47 import android.view.Menu;
48 import android.view.MenuItem;
49 import android.view.View.OnClickListener;
50 import android.view.View.OnCreateContextMenuListener;
51 import android.view.View;
52 import android.view.ViewGroup;
53 import android.view.Window;
54 import android.view.WindowManager;
55 import android.view.animation.Animation;
56 import android.view.animation.AnimationUtils;
57 import android.view.animation.TranslateAnimation;
58 import android.widget.AbsoluteLayout;
59 import android.widget.AdapterView.AdapterContextMenuInfo;
60 import android.widget.AdapterView.OnItemClickListener;
61 import android.widget.AdapterView;
62 import android.widget.Button;
63 import android.widget.CheckBox;
64 import android.widget.ImageView;
65 import android.widget.TextView;
67 import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
68 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
69 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
71 import java.io.IOException;
72 import java.io.InputStream;
73 import java.text.DateFormat;
74 import java.util.Date;
75 import java.util.Locale;
76 import java.util.Random;
79 * DeskClock clock view for desk docks.
81 public class DeskClock extends Activity {
82 private static final boolean DEBUG = false;
84 private static final String LOG_TAG = "DeskClock";
86 // Intent used to start the music player.
87 private static final String MUSIC_NOW_PLAYING = "com.android.music.PLAYBACK_VIEWER";
89 // Interval between polls of the weather widget. Its refresh period is
90 // likely to be much longer (~3h), but we want to pick up any changes
92 private final long FETCH_WEATHER_DELAY = 5 * 60 * 1000; // 5 min
94 // Delay before engaging the burn-in protection mode (green-on-black).
95 private final long SCREEN_SAVER_TIMEOUT = 10 * 60 * 1000; // 10 min
97 // Repositioning delay in screen saver.
98 private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
100 // Color to use for text & graphics in screen saver mode.
101 private final int SCREEN_SAVER_COLOR = 0xFF008000;
102 private final int SCREEN_SAVER_COLOR_DIM = 0xFF003000;
104 // Internal message IDs.
105 private final int FETCH_WEATHER_DATA_MSG = 0x1000;
106 private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
107 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000;
108 private final int SCREEN_SAVER_MOVE_MSG = 0x2001;
110 // Weather widget query information.
111 private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
112 private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
113 private static final String WEATHER_CONTENT_PATH = "/weather/current";
114 private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
124 // State variables follow.
125 private DigitalClock mTime;
126 private TextView mDate;
128 private TextView mNextAlarm = null;
129 private TextView mBatteryDisplay;
131 private TextView mWeatherHighTemperature;
132 private TextView mWeatherLowTemperature;
133 private TextView mWeatherLocation;
134 private ImageView mWeatherIcon;
136 private String mWeatherHighTemperatureString;
137 private String mWeatherLowTemperatureString;
138 private String mWeatherLocationString;
139 private Drawable mWeatherIconDrawable;
141 private Resources mGenieResources = null;
143 private boolean mDimmed = false;
144 private boolean mScreenSaverMode = false;
146 private DateFormat mDateFormat;
148 private int mBatteryLevel = -1;
149 private boolean mPluggedIn = false;
151 private int mIdleTimeoutEpoch = 0;
153 private boolean mWeatherFetchScheduled = false;
157 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
159 public void onReceive(Context context, Intent intent) {
160 final String action = intent.getAction();
161 if (Intent.ACTION_DATE_CHANGED.equals(action)) {
163 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
165 intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
166 intent.getIntExtra("level", 0));
171 private final Handler mHandy = new Handler() {
173 public void handleMessage(Message m) {
174 if (m.what == FETCH_WEATHER_DATA_MSG) {
175 if (!mWeatherFetchScheduled) return;
176 mWeatherFetchScheduled = false;
177 new Thread() { public void run() { fetchWeatherData(); } }.start();
178 scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
179 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
180 updateWeatherDisplay();
181 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
182 if (m.arg1 == mIdleTimeoutEpoch) {
185 } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
192 private void moveScreenSaver() {
193 moveScreenSaverTo(-1,-1);
195 private void moveScreenSaverTo(int x, int y) {
196 if (!mScreenSaverMode) return;
198 final View time_date = findViewById(R.id.time_date);
201 final TranslateAnimation anim = new TranslateAnimation(
202 Animation.RELATIVE_TO_SELF, 0, // fromX
203 Animation.RELATIVE_TO_PARENT, 0.5f, // toX
204 Animation.RELATIVE_TO_SELF, 0, // fromY
205 Animation.RELATIVE_TO_PARENT, 0.5f // toY
207 anim.setDuration(1000);
208 anim.setInterpolator(new android.view.animation.AccelerateDecelerateInterpolator());
209 anim.setFillEnabled(true);
210 anim.setFillAfter(true);
211 time_date.startAnimation(anim);
214 DisplayMetrics metrics = new DisplayMetrics();
215 getWindowManager().getDefaultDisplay().getMetrics(metrics);
217 if (x < 0 || y < 0) {
218 int myWidth = time_date.getMeasuredWidth();
219 int myHeight = time_date.getMeasuredHeight();
220 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
221 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
224 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
225 System.currentTimeMillis(), x, y));
227 time_date.setLayoutParams(new AbsoluteLayout.LayoutParams(
228 ViewGroup.LayoutParams.WRAP_CONTENT,
229 ViewGroup.LayoutParams.WRAP_CONTENT,
233 // Synchronize our jumping so that it happens exactly on the second.
234 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
235 SCREEN_SAVER_MOVE_DELAY +
236 (1000 - (System.currentTimeMillis() % 1000)));
239 private void setWakeLock(boolean hold) {
240 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
241 Window win = getWindow();
242 WindowManager.LayoutParams winParams = win.getAttributes();
243 winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
244 winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
245 winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
247 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
249 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
250 win.setAttributes(winParams);
253 private void restoreScreen() {
254 if (!mScreenSaverMode) return;
255 if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
256 mScreenSaverMode = false;
258 doDim(false); // restores previous dim mode
262 // Special screen-saver mode for OLED displays that burn in quickly
263 private void saveScreen() {
264 if (mScreenSaverMode) return;
265 if (DEBUG) Log.d(LOG_TAG, "saveScreen");
267 // quickly stash away the x/y of the current date
268 final View oldTimeDate = findViewById(R.id.time_date);
269 int oldLoc[] = new int[2];
270 oldTimeDate.getLocationOnScreen(oldLoc);
272 mScreenSaverMode = true;
273 Window win = getWindow();
274 WindowManager.LayoutParams winParams = win.getAttributes();
275 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
276 win.setAttributes(winParams);
278 // give up any internal focus before we switch layouts
279 final View focused = getCurrentFocus();
280 if (focused != null) focused.clearFocus();
282 setContentView(R.layout.desk_clock_saver);
284 mTime = (DigitalClock) findViewById(R.id.time);
285 mDate = (TextView) findViewById(R.id.date);
287 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
289 ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
290 ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
291 mDate.setTextColor(color);
295 mWeatherHighTemperature =
296 mWeatherLowTemperature =
297 mWeatherLocation = null;
302 moveScreenSaverTo(oldLoc[0], oldLoc[1]);
306 public void onUserInteraction() {
307 if (mScreenSaverMode)
311 private boolean supportsWeather() {
312 return (mGenieResources != null);
315 private void scheduleWeatherFetchDelayed(long delay) {
316 if (mWeatherFetchScheduled) return;
318 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
320 mWeatherFetchScheduled = true;
322 mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
325 private void unscheduleWeatherFetch() {
326 mWeatherFetchScheduled = false;
329 private static final boolean sCelsius;
331 String cc = Locale.getDefault().getCountry().toLowerCase();
332 sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
335 private static int celsiusToLocal(int tempC) {
336 return sCelsius ? tempC : (int) Math.round(tempC * 1.8f + 32);
339 private void fetchWeatherData() {
340 // if we couldn't load the weather widget's resources, we simply
341 // assume it's not present on the device.
342 if (mGenieResources == null) return;
344 Uri queryUri = new Uri.Builder()
345 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
346 .authority(WEATHER_CONTENT_AUTHORITY)
347 .path(WEATHER_CONTENT_PATH)
348 .appendPath(new Long(System.currentTimeMillis()).toString())
351 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
357 WEATHER_CONTENT_COLUMNS,
361 } catch (RuntimeException e) {
362 Log.e(LOG_TAG, "Weather query failed", e);
366 if (cur != null && cur.moveToFirst()) {
368 java.lang.StringBuilder sb =
369 new java.lang.StringBuilder("Weather query result: {");
370 for(int i=0; i<cur.getColumnCount(); i++) {
371 if (i>0) sb.append(", ");
372 sb.append(cur.getColumnName(i))
374 .append(cur.getString(i));
377 Log.d(LOG_TAG, sb.toString());
380 mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
381 cur.getColumnIndexOrThrow("iconResId")));
382 mWeatherHighTemperatureString = String.format("%d\u00b0",
383 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
384 mWeatherLowTemperatureString = String.format("%d\u00b0",
385 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
386 mWeatherLocationString = cur.getString(
387 cur.getColumnIndexOrThrow("location"));
389 Log.w(LOG_TAG, "No weather information available (cur="
391 mWeatherIconDrawable = null;
392 mWeatherHighTemperatureString = "";
393 mWeatherLowTemperatureString = "";
394 mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
397 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
400 private void refreshWeather() {
401 if (supportsWeather())
402 scheduleWeatherFetchDelayed(0);
403 updateWeatherDisplay(); // in case we have it cached
406 private void updateWeatherDisplay() {
407 if (mWeatherHighTemperature == null) return;
409 mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
410 mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
411 mWeatherLocation.setText(mWeatherLocationString);
412 mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
415 // Adapted from KeyguardUpdateMonitor.java
416 private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
417 final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
418 if (pluggedIn != mPluggedIn) {
419 setWakeLock(pluggedIn);
421 if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
422 mBatteryLevel = batteryLevel;
423 mPluggedIn = pluggedIn;
428 private void refreshBattery() {
429 if (mBatteryDisplay == null) return;
431 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
432 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
433 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
434 mBatteryDisplay.setText(
435 getString(R.string.battery_charging_level, mBatteryLevel));
436 mBatteryDisplay.setVisibility(View.VISIBLE);
438 mBatteryDisplay.setVisibility(View.INVISIBLE);
442 private void refreshDate() {
443 mDate.setText(mDateFormat.format(new Date()));
446 private void refreshAlarm() {
447 if (mNextAlarm == null) return;
449 String nextAlarm = Settings.System.getString(getContentResolver(),
450 Settings.System.NEXT_ALARM_FORMATTED);
451 if (!TextUtils.isEmpty(nextAlarm)) {
452 mNextAlarm.setText(nextAlarm);
453 //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
454 // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
455 mNextAlarm.setVisibility(View.VISIBLE);
457 mNextAlarm.setVisibility(View.INVISIBLE);
461 private void refreshAll() {
468 private void doDim(boolean fade) {
469 View tintView = findViewById(R.id.window_tint);
470 if (tintView == null) return;
472 Window win = getWindow();
473 WindowManager.LayoutParams winParams = win.getAttributes();
476 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
477 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
479 // dim the wallpaper somewhat (how much is determined below)
480 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
483 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
484 winParams.dimAmount = 0.5f; // pump up contrast in dim mode
486 // show the window tint
487 tintView.startAnimation(AnimationUtils.loadAnimation(this,
489 : R.anim.dim_instant));
491 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
492 winParams.dimAmount = 0.2f; // lower contrast in normal mode
494 // hide the window tint
495 tintView.startAnimation(AnimationUtils.loadAnimation(this,
497 : R.anim.undim_instant));
500 win.setAttributes(winParams);
504 public void onResume() {
506 if (DEBUG) Log.d(LOG_TAG, "onResume");
508 // reload the date format in case the user has changed settings
510 mDateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
512 IntentFilter filter = new IntentFilter();
513 filter.addAction(Intent.ACTION_DATE_CHANGED);
514 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
515 registerReceiver(mIntentReceiver, filter);
519 refreshAll(); // will schedule periodic weather fetch
521 setWakeLock(mPluggedIn);
524 mHandy.sendMessageDelayed(
525 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
526 SCREEN_SAVER_TIMEOUT);
530 public void onPause() {
531 if (DEBUG) Log.d(LOG_TAG, "onPause");
533 // Turn off the screen saver.
536 // Avoid situations where the user launches Alarm Clock and is
537 // surprised to find it in dim mode (because it was last used in dim
538 // mode, but that last use is long in the past).
541 // Other things we don't want to be doing in the background.
542 unregisterReceiver(mIntentReceiver);
543 unscheduleWeatherFetch();
549 private void initViews() {
550 // give up any internal focus before we switch layouts
551 final View focused = getCurrentFocus();
552 if (focused != null) focused.clearFocus();
554 setContentView(R.layout.desk_clock);
556 mTime = (DigitalClock) findViewById(R.id.time);
557 mDate = (TextView) findViewById(R.id.date);
558 mBatteryDisplay = (TextView) findViewById(R.id.battery);
560 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
561 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
562 mWeatherLocation = (TextView) findViewById(R.id.weather_location);
563 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
565 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
567 final Button alarmButton = (Button) findViewById(R.id.alarm_button);
568 alarmButton.setOnClickListener(new View.OnClickListener() {
569 public void onClick(View v) {
570 startActivity(new Intent(DeskClock.this, AlarmClock.class));
574 final Button galleryButton = (Button) findViewById(R.id.gallery_button);
575 galleryButton.setOnClickListener(new View.OnClickListener() {
576 public void onClick(View v) {
578 startActivity(new Intent(
580 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
581 } catch (android.content.ActivityNotFoundException e) {
582 Log.e(LOG_TAG, "Couldn't launch image browser", e);
587 final Button musicButton = (Button) findViewById(R.id.music_button);
588 musicButton.setOnClickListener(new View.OnClickListener() {
589 public void onClick(View v) {
591 startActivity(new Intent(MUSIC_NOW_PLAYING));
592 } catch (android.content.ActivityNotFoundException e) {
593 Log.e(LOG_TAG, "Couldn't launch music browser", e);
598 final Button homeButton = (Button) findViewById(R.id.home_button);
599 homeButton.setOnClickListener(new View.OnClickListener() {
600 public void onClick(View v) {
602 new Intent(Intent.ACTION_MAIN)
603 .addCategory(Intent.CATEGORY_HOME));
607 final Button nightmodeButton = (Button) findViewById(R.id.nightmode_button);
608 nightmodeButton.setOnClickListener(new View.OnClickListener() {
609 public void onClick(View v) {
615 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
616 public boolean onLongClick(View v) {
624 public void onConfigurationChanged(Configuration newConfig) {
625 super.onConfigurationChanged(newConfig);
626 if (!mScreenSaverMode) {
634 protected void onCreate(Bundle icicle) {
635 super.onCreate(icicle);
640 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
641 } catch (PackageManager.NameNotFoundException e) {
642 // no weather info available
643 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");