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.ImageButton;
65 import android.widget.ImageView;
66 import android.widget.TextView;
68 import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
69 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
70 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
72 import java.io.IOException;
73 import java.io.InputStream;
74 import java.text.DateFormat;
75 import java.util.Date;
76 import java.util.Locale;
77 import java.util.Random;
80 * DeskClock clock view for desk docks.
82 public class DeskClock extends Activity {
83 private static final boolean DEBUG = false;
85 private static final String LOG_TAG = "DeskClock";
87 // Intent used to start the music player.
88 private static final String MUSIC_NOW_PLAYING = "com.android.music.PLAYBACK_VIEWER";
90 // Interval between polls of the weather widget. Its refresh period is
91 // likely to be much longer (~3h), but we want to pick up any changes
93 private final long FETCH_WEATHER_DELAY = 5 * 60 * 1000; // 5 min
95 // Delay before engaging the burn-in protection mode (green-on-black).
96 private final long SCREEN_SAVER_TIMEOUT = 10 * 60 * 1000; // 10 min
98 // Repositioning delay in screen saver.
99 private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
101 // Color to use for text & graphics in screen saver mode.
102 private final int SCREEN_SAVER_COLOR = 0xFF308030;
103 private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018;
105 // Internal message IDs.
106 private final int FETCH_WEATHER_DATA_MSG = 0x1000;
107 private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
108 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000;
109 private final int SCREEN_SAVER_MOVE_MSG = 0x2001;
111 // Weather widget query information.
112 private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
113 private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
114 private static final String WEATHER_CONTENT_PATH = "/weather/current";
115 private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
125 // State variables follow.
126 private DigitalClock mTime;
127 private TextView mDate;
129 private TextView mNextAlarm = null;
130 private TextView mBatteryDisplay;
132 private TextView mWeatherHighTemperature;
133 private TextView mWeatherLowTemperature;
134 private TextView mWeatherLocation;
135 private ImageView mWeatherIcon;
137 private String mWeatherHighTemperatureString;
138 private String mWeatherLowTemperatureString;
139 private String mWeatherLocationString;
140 private Drawable mWeatherIconDrawable;
142 private Resources mGenieResources = null;
144 private boolean mDimmed = false;
145 private boolean mScreenSaverMode = false;
147 private DateFormat mDateFormat;
149 private int mBatteryLevel = -1;
150 private boolean mPluggedIn = false;
152 private int mIdleTimeoutEpoch = 0;
154 private boolean mWeatherFetchScheduled = false;
158 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
160 public void onReceive(Context context, Intent intent) {
161 final String action = intent.getAction();
162 if (Intent.ACTION_DATE_CHANGED.equals(action)) {
164 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
166 intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
167 intent.getIntExtra("level", 0));
172 private final Handler mHandy = new Handler() {
174 public void handleMessage(Message m) {
175 if (m.what == FETCH_WEATHER_DATA_MSG) {
176 if (!mWeatherFetchScheduled) return;
177 mWeatherFetchScheduled = false;
178 new Thread() { public void run() { fetchWeatherData(); } }.start();
179 scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
180 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
181 updateWeatherDisplay();
182 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
183 if (m.arg1 == mIdleTimeoutEpoch) {
186 } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
193 private void moveScreenSaver() {
194 moveScreenSaverTo(-1,-1);
196 private void moveScreenSaverTo(int x, int y) {
197 if (!mScreenSaverMode) return;
199 final View time_date = findViewById(R.id.time_date);
201 DisplayMetrics metrics = new DisplayMetrics();
202 getWindowManager().getDefaultDisplay().getMetrics(metrics);
204 if (x < 0 || y < 0) {
205 int myWidth = time_date.getMeasuredWidth();
206 int myHeight = time_date.getMeasuredHeight();
207 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
208 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
211 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
212 System.currentTimeMillis(), x, y));
214 time_date.setLayoutParams(new AbsoluteLayout.LayoutParams(
215 ViewGroup.LayoutParams.WRAP_CONTENT,
216 ViewGroup.LayoutParams.WRAP_CONTENT,
220 // Synchronize our jumping so that it happens exactly on the second.
221 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
222 SCREEN_SAVER_MOVE_DELAY +
223 (1000 - (System.currentTimeMillis() % 1000)));
226 private void setWakeLock(boolean hold) {
227 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
228 Window win = getWindow();
229 WindowManager.LayoutParams winParams = win.getAttributes();
230 winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
231 winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
232 winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
234 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
236 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
237 win.setAttributes(winParams);
240 private void restoreScreen() {
241 if (!mScreenSaverMode) return;
242 if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
243 mScreenSaverMode = false;
245 doDim(false); // restores previous dim mode
249 // Special screen-saver mode for OLED displays that burn in quickly
250 private void saveScreen() {
251 if (mScreenSaverMode) return;
252 if (DEBUG) Log.d(LOG_TAG, "saveScreen");
254 // quickly stash away the x/y of the current date
255 final View oldTimeDate = findViewById(R.id.time_date);
256 int oldLoc[] = new int[2];
257 oldTimeDate.getLocationOnScreen(oldLoc);
259 mScreenSaverMode = true;
260 Window win = getWindow();
261 WindowManager.LayoutParams winParams = win.getAttributes();
262 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
263 win.setAttributes(winParams);
265 // give up any internal focus before we switch layouts
266 final View focused = getCurrentFocus();
267 if (focused != null) focused.clearFocus();
269 setContentView(R.layout.desk_clock_saver);
271 mTime = (DigitalClock) findViewById(R.id.time);
272 mDate = (TextView) findViewById(R.id.date);
274 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
276 ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
277 ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
278 mDate.setTextColor(color);
282 mWeatherHighTemperature =
283 mWeatherLowTemperature =
284 mWeatherLocation = null;
289 moveScreenSaverTo(oldLoc[0], oldLoc[1]);
293 public void onUserInteraction() {
294 if (mScreenSaverMode)
298 private boolean supportsWeather() {
299 return (mGenieResources != null);
302 private void scheduleWeatherFetchDelayed(long delay) {
303 if (mWeatherFetchScheduled) return;
305 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
307 mWeatherFetchScheduled = true;
309 mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
312 private void unscheduleWeatherFetch() {
313 mWeatherFetchScheduled = false;
316 private static final boolean sCelsius;
318 String cc = Locale.getDefault().getCountry().toLowerCase();
319 sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
322 private static int celsiusToLocal(int tempC) {
323 return sCelsius ? tempC : (int) Math.round(tempC * 1.8f + 32);
326 private void fetchWeatherData() {
327 // if we couldn't load the weather widget's resources, we simply
328 // assume it's not present on the device.
329 if (mGenieResources == null) return;
331 Uri queryUri = new Uri.Builder()
332 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
333 .authority(WEATHER_CONTENT_AUTHORITY)
334 .path(WEATHER_CONTENT_PATH)
335 .appendPath(new Long(System.currentTimeMillis()).toString())
338 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
344 WEATHER_CONTENT_COLUMNS,
348 } catch (RuntimeException e) {
349 Log.e(LOG_TAG, "Weather query failed", e);
353 if (cur != null && cur.moveToFirst()) {
355 java.lang.StringBuilder sb =
356 new java.lang.StringBuilder("Weather query result: {");
357 for(int i=0; i<cur.getColumnCount(); i++) {
358 if (i>0) sb.append(", ");
359 sb.append(cur.getColumnName(i))
361 .append(cur.getString(i));
364 Log.d(LOG_TAG, sb.toString());
367 mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
368 cur.getColumnIndexOrThrow("iconResId")));
369 mWeatherHighTemperatureString = String.format("%d\u00b0",
370 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
371 mWeatherLowTemperatureString = String.format("%d\u00b0",
372 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
373 mWeatherLocationString = cur.getString(
374 cur.getColumnIndexOrThrow("location"));
376 Log.w(LOG_TAG, "No weather information available (cur="
378 mWeatherIconDrawable = null;
379 mWeatherHighTemperatureString = "";
380 mWeatherLowTemperatureString = "";
381 mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
384 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
387 private void refreshWeather() {
388 if (supportsWeather())
389 scheduleWeatherFetchDelayed(0);
390 updateWeatherDisplay(); // in case we have it cached
393 private void updateWeatherDisplay() {
394 if (mWeatherHighTemperature == null) return;
396 mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
397 mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
398 mWeatherLocation.setText(mWeatherLocationString);
399 mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
402 // Adapted from KeyguardUpdateMonitor.java
403 private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
404 final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
405 if (pluggedIn != mPluggedIn) {
406 setWakeLock(pluggedIn);
408 if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
409 mBatteryLevel = batteryLevel;
410 mPluggedIn = pluggedIn;
415 private void refreshBattery() {
416 if (mBatteryDisplay == null) return;
418 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
419 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
420 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
421 mBatteryDisplay.setText(
422 getString(R.string.battery_charging_level, mBatteryLevel));
423 mBatteryDisplay.setVisibility(View.VISIBLE);
425 mBatteryDisplay.setVisibility(View.INVISIBLE);
429 private void refreshDate() {
430 mDate.setText(mDateFormat.format(new Date()));
433 private void refreshAlarm() {
434 if (mNextAlarm == null) return;
436 String nextAlarm = Settings.System.getString(getContentResolver(),
437 Settings.System.NEXT_ALARM_FORMATTED);
438 if (!TextUtils.isEmpty(nextAlarm)) {
439 mNextAlarm.setText(nextAlarm);
440 //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
441 // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
442 mNextAlarm.setVisibility(View.VISIBLE);
444 mNextAlarm.setVisibility(View.INVISIBLE);
448 private void refreshAll() {
455 private void doDim(boolean fade) {
456 View tintView = findViewById(R.id.window_tint);
457 if (tintView == null) return;
459 Window win = getWindow();
460 WindowManager.LayoutParams winParams = win.getAttributes();
463 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
464 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
466 // dim the wallpaper somewhat (how much is determined below)
467 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
470 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
471 winParams.dimAmount = 0.67f; // pump up contrast in dim mode
473 // show the window tint
474 tintView.startAnimation(AnimationUtils.loadAnimation(this,
476 : R.anim.dim_instant));
478 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
479 winParams.dimAmount = 0.5f; // lower contrast in normal mode
481 // hide the window tint
482 tintView.startAnimation(AnimationUtils.loadAnimation(this,
484 : R.anim.undim_instant));
487 win.setAttributes(winParams);
491 public void onResume() {
493 if (DEBUG) Log.d(LOG_TAG, "onResume");
495 // reload the date format in case the user has changed settings
497 mDateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
499 IntentFilter filter = new IntentFilter();
500 filter.addAction(Intent.ACTION_DATE_CHANGED);
501 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
502 registerReceiver(mIntentReceiver, filter);
506 refreshAll(); // will schedule periodic weather fetch
508 setWakeLock(mPluggedIn);
511 mHandy.sendMessageDelayed(
512 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
513 SCREEN_SAVER_TIMEOUT);
517 public void onPause() {
518 if (DEBUG) Log.d(LOG_TAG, "onPause");
520 // Turn off the screen saver.
523 // Avoid situations where the user launches Alarm Clock and is
524 // surprised to find it in dim mode (because it was last used in dim
525 // mode, but that last use is long in the past).
528 // Other things we don't want to be doing in the background.
529 unregisterReceiver(mIntentReceiver);
530 unscheduleWeatherFetch();
536 private void initViews() {
537 // give up any internal focus before we switch layouts
538 final View focused = getCurrentFocus();
539 if (focused != null) focused.clearFocus();
541 setContentView(R.layout.desk_clock);
543 mTime = (DigitalClock) findViewById(R.id.time);
544 mDate = (TextView) findViewById(R.id.date);
545 mBatteryDisplay = (TextView) findViewById(R.id.battery);
547 mTime.getRootView().requestFocus();
549 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
550 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
551 mWeatherLocation = (TextView) findViewById(R.id.weather_location);
552 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
554 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
556 final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
557 alarmButton.setOnClickListener(new View.OnClickListener() {
558 public void onClick(View v) {
559 startActivity(new Intent(DeskClock.this, AlarmClock.class));
563 final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
564 galleryButton.setOnClickListener(new View.OnClickListener() {
565 public void onClick(View v) {
567 startActivity(new Intent(
569 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
570 .putExtra("slideshow", true));
571 } catch (android.content.ActivityNotFoundException e) {
572 Log.e(LOG_TAG, "Couldn't launch image browser", e);
577 final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
578 musicButton.setOnClickListener(new View.OnClickListener() {
579 public void onClick(View v) {
581 startActivity(new Intent(MUSIC_NOW_PLAYING));
582 } catch (android.content.ActivityNotFoundException e) {
583 Log.e(LOG_TAG, "Couldn't launch music browser", e);
588 final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
589 homeButton.setOnClickListener(new View.OnClickListener() {
590 public void onClick(View v) {
592 new Intent(Intent.ACTION_MAIN)
593 .addCategory(Intent.CATEGORY_HOME));
597 final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
598 nightmodeButton.setOnClickListener(new View.OnClickListener() {
599 public void onClick(View v) {
605 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
606 public boolean onLongClick(View v) {
612 final View weatherView = findViewById(R.id.weather);
613 weatherView.setOnClickListener(new View.OnClickListener() {
614 public void onClick(View v) {
615 if (!supportsWeather()) return;
617 Intent genieAppQuery = getPackageManager().getLaunchIntentForPackage(GENIE_PACKAGE_ID);
618 if (genieAppQuery != null) {
619 startActivity(genieAppQuery);
626 public void onConfigurationChanged(Configuration newConfig) {
627 super.onConfigurationChanged(newConfig);
628 if (!mScreenSaverMode) {
636 protected void onCreate(Bundle icicle) {
637 super.onCreate(icicle);
642 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
643 } catch (PackageManager.NameNotFoundException e) {
644 // no weather info available
645 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");