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 private static final String MUSIC_NOW_PLAYING_ACTIVITY = "com.android.music.PLAYBACK_VIEWER";
88 private final long FETCH_WEATHER_DELAY = 60 * 60 * 1000; // 1 hr
89 private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min
90 private final long SCREEN_SAVER_MOVE_DELAY = 5 * 1000; // 15 sec
92 private final int FETCH_WEATHER_DATA_MSG = 0x1000;
93 private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
94 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000;
95 private final int SCREEN_SAVER_MOVE_MSG = 0x2001;
97 private final int SCREEN_SAVER_COLOR = 0xFF008000;
98 private final int SCREEN_SAVER_COLOR_DIM = 0xFF003000;
100 private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
101 private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
102 private static final String WEATHER_CONTENT_PATH = "/weather/current";
103 private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
113 private DigitalClock mTime;
114 private TextView mDate;
116 private TextView mNextAlarm = null;
117 private TextView mBatteryDisplay;
119 private TextView mWeatherHighTemperature;
120 private TextView mWeatherLowTemperature;
121 private TextView mWeatherLocation;
122 private ImageView mWeatherIcon;
124 private String mWeatherHighTemperatureString;
125 private String mWeatherLowTemperatureString;
126 private String mWeatherLocationString;
127 private Drawable mWeatherIconDrawable;
129 private Resources mGenieResources = null;
131 private boolean mDimmed = false;
132 private boolean mScreenSaverMode = false;
134 private DateFormat mDateFormat;
136 private int mBatteryLevel = -1;
137 private boolean mPluggedIn = false;
139 private int mIdleTimeoutEpoch = 0;
141 private boolean mWeatherFetchScheduled = false;
145 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
147 public void onReceive(Context context, Intent intent) {
148 final String action = intent.getAction();
149 if (Intent.ACTION_DATE_CHANGED.equals(action)) {
151 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
153 intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
154 intent.getIntExtra("level", 0));
159 private final Handler mHandy = new Handler() {
161 public void handleMessage(Message m) {
162 if (DEBUG) Log.d(LOG_TAG, "handleMessage: " + m.toString());
164 if (m.what == FETCH_WEATHER_DATA_MSG) {
165 if (!mWeatherFetchScheduled) return;
166 mWeatherFetchScheduled = false;
167 new Thread() { public void run() { fetchWeatherData(); } }.start();
168 scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
169 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
170 updateWeatherDisplay();
171 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
172 if (m.arg1 == mIdleTimeoutEpoch) {
175 } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
180 private void moveScreenSaver() {
181 moveScreenSaverTo(-1,-1);
183 private void moveScreenSaverTo(int x, int y) {
184 if (!mScreenSaverMode) return;
186 final View time_date = findViewById(R.id.time_date);
189 final TranslateAnimation anim = new TranslateAnimation(
190 Animation.RELATIVE_TO_SELF, 0, // fromX
191 Animation.RELATIVE_TO_PARENT, 0.5f, // toX
192 Animation.RELATIVE_TO_SELF, 0, // fromY
193 Animation.RELATIVE_TO_PARENT, 0.5f // toY
195 anim.setDuration(1000);
196 anim.setInterpolator(new android.view.animation.AccelerateDecelerateInterpolator());
197 anim.setFillEnabled(true);
198 anim.setFillAfter(true);
199 time_date.startAnimation(anim);
202 DisplayMetrics metrics = new DisplayMetrics();
203 getWindowManager().getDefaultDisplay().getMetrics(metrics);
205 if (x < 0 || y < 0) {
206 int myWidth = time_date.getMeasuredWidth();
207 int myHeight = time_date.getMeasuredHeight();
208 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
209 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
212 time_date.setLayoutParams(new AbsoluteLayout.LayoutParams(
213 ViewGroup.LayoutParams.WRAP_CONTENT,
214 ViewGroup.LayoutParams.WRAP_CONTENT,
218 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG, SCREEN_SAVER_MOVE_DELAY);
221 private void setWakeLock(boolean hold) {
222 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
223 Window win = getWindow();
224 WindowManager.LayoutParams winParams = win.getAttributes();
225 winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
227 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
229 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
230 win.setAttributes(winParams);
233 private void restoreScreen() {
234 if (!mScreenSaverMode) return;
235 mScreenSaverMode = false;
237 doDim(false); // restores previous dim mode
241 // Special screen-saver mode for OLED displays that burn in quickly
242 private void saveScreen() {
243 if (mScreenSaverMode) return;
245 // quickly stash away the x/y of the current date
246 final View oldTimeDate = findViewById(R.id.time_date);
247 int oldLoc[] = new int[2];
248 oldTimeDate.getLocationOnScreen(oldLoc);
250 mScreenSaverMode = true;
251 Window win = getWindow();
252 WindowManager.LayoutParams winParams = win.getAttributes();
253 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
254 win.setAttributes(winParams);
256 // give up any internal focus before we switch layouts
257 final View focused = getCurrentFocus();
258 if (focused != null) focused.clearFocus();
260 setContentView(R.layout.desk_clock_saver);
262 mTime = (DigitalClock) findViewById(R.id.time);
263 mDate = (TextView) findViewById(R.id.date);
265 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
267 ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
268 ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
269 mDate.setTextColor(color);
273 mWeatherHighTemperature =
274 mWeatherLowTemperature =
275 mWeatherLocation = null;
280 moveScreenSaverTo(oldLoc[0], oldLoc[1]);
284 public void onUserInteraction() {
285 if (mScreenSaverMode)
289 private boolean supportsWeather() {
290 return (mGenieResources != null);
293 private void scheduleWeatherFetchDelayed(long delay) {
294 if (mWeatherFetchScheduled) return;
296 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
298 mWeatherFetchScheduled = true;
300 mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
303 private void unscheduleWeatherFetch() {
304 mWeatherFetchScheduled = false;
307 private static final boolean sCelsius;
309 String cc = Locale.getDefault().getCountry().toLowerCase();
310 sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
313 private static int celsiusToLocal(int tempC) {
314 return sCelsius ? tempC : (int)(tempC * 1.8f + 32);
317 private void fetchWeatherData() {
318 // if we couldn't load the weather widget's resources, we simply
319 // assume it's not present on the device.
320 if (mGenieResources == null) return;
322 Uri queryUri = new Uri.Builder()
323 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
324 .authority(WEATHER_CONTENT_AUTHORITY)
325 .path(WEATHER_CONTENT_PATH)
326 .appendPath(new Long(System.currentTimeMillis()).toString())
329 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
335 WEATHER_CONTENT_COLUMNS,
339 } catch (RuntimeException e) {
340 Log.e(LOG_TAG, "Weather query failed", e);
344 if (cur != null && cur.moveToFirst()) {
345 mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
346 cur.getColumnIndexOrThrow("iconResId")));
347 mWeatherHighTemperatureString = String.format("%d\u00b0",
348 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
349 mWeatherLowTemperatureString = String.format("%d\u00b0",
350 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
351 mWeatherLocationString = cur.getString(
352 cur.getColumnIndexOrThrow("location"));
354 Log.w(LOG_TAG, "No weather information available (cur="
356 mWeatherIconDrawable = null;
357 mWeatherHighTemperatureString = "";
358 mWeatherLowTemperatureString = "";
359 mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
362 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
365 private void refreshWeather() {
366 if (supportsWeather())
367 scheduleWeatherFetchDelayed(0);
368 updateWeatherDisplay(); // in case we have it cached
371 private void updateWeatherDisplay() {
372 if (mWeatherHighTemperature == null) return;
374 mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
375 mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
376 mWeatherLocation.setText(mWeatherLocationString);
377 mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
380 // Adapted from KeyguardUpdateMonitor.java
381 private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
382 final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
383 if (pluggedIn != mPluggedIn) {
384 setWakeLock(pluggedIn);
386 if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
387 mBatteryLevel = batteryLevel;
388 mPluggedIn = pluggedIn;
393 private void refreshBattery() {
394 if (mBatteryDisplay == null) return;
396 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
397 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
398 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
399 mBatteryDisplay.setText(
400 getString(R.string.battery_charging_level, mBatteryLevel));
401 mBatteryDisplay.setVisibility(View.VISIBLE);
403 mBatteryDisplay.setVisibility(View.INVISIBLE);
407 private void refreshDate() {
408 mDate.setText(mDateFormat.format(new Date()));
411 private void refreshAlarm() {
412 if (mNextAlarm == null) return;
414 String nextAlarm = Settings.System.getString(getContentResolver(),
415 Settings.System.NEXT_ALARM_FORMATTED);
416 if (!TextUtils.isEmpty(nextAlarm)) {
417 mNextAlarm.setText(nextAlarm);
418 //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
419 // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
420 mNextAlarm.setVisibility(View.VISIBLE);
422 mNextAlarm.setVisibility(View.INVISIBLE);
426 private void refreshAll() {
433 private void doDim(boolean fade) {
434 View tintView = findViewById(R.id.window_tint);
435 if (tintView == null) return;
437 Window win = getWindow();
438 WindowManager.LayoutParams winParams = win.getAttributes();
441 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
442 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
444 // dim the wallpaper somewhat (how much is determined below)
445 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
448 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
449 winParams.dimAmount = 0.5f; // pump up contrast in dim mode
451 // show the window tint
452 tintView.startAnimation(AnimationUtils.loadAnimation(this,
454 : R.anim.dim_instant));
456 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
457 winParams.dimAmount = 0.2f; // lower contrast in normal mode
459 // hide the window tint
460 tintView.startAnimation(AnimationUtils.loadAnimation(this,
462 : R.anim.undim_instant));
465 win.setAttributes(winParams);
469 public void onResume() {
471 // NB: To avoid situations where the user launches Alarm Clock and is
472 // surprised to find it in dim mode (because it was last used in dim
473 // mode, but that last use is long in the past), we always un-dim upon
474 // bringing the activity to the foregreound.
477 // reload the date format in case the user has changed settings
479 mDateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
481 IntentFilter filter = new IntentFilter();
482 filter.addAction(Intent.ACTION_DATE_CHANGED);
483 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
484 registerReceiver(mIntentReceiver, filter);
489 setWakeLock(mPluggedIn);
492 mHandy.sendMessageDelayed(
493 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
494 SCREEN_SAVER_TIMEOUT);
498 public void onPause() {
500 unregisterReceiver(mIntentReceiver);
501 unscheduleWeatherFetch();
505 private void initViews() {
506 // give up any internal focus before we switch layouts
507 final View focused = getCurrentFocus();
508 if (focused != null) focused.clearFocus();
510 setContentView(R.layout.desk_clock);
512 mTime = (DigitalClock) findViewById(R.id.time);
513 mDate = (TextView) findViewById(R.id.date);
514 mBatteryDisplay = (TextView) findViewById(R.id.battery);
516 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
517 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
518 mWeatherLocation = (TextView) findViewById(R.id.weather_location);
519 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
521 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
523 final Button alarmButton = (Button) findViewById(R.id.alarm_button);
524 alarmButton.setOnClickListener(new View.OnClickListener() {
525 public void onClick(View v) {
526 startActivity(new Intent(DeskClock.this, AlarmClock.class));
530 final Button galleryButton = (Button) findViewById(R.id.gallery_button);
531 galleryButton.setOnClickListener(new View.OnClickListener() {
532 public void onClick(View v) {
534 startActivity(new Intent(
536 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
537 } catch (android.content.ActivityNotFoundException e) {
538 Log.e(LOG_TAG, "Couldn't launch image browser", e);
543 final Button musicButton = (Button) findViewById(R.id.music_button);
544 musicButton.setOnClickListener(new View.OnClickListener() {
545 public void onClick(View v) {
547 startActivity(new Intent(MUSIC_NOW_PLAYING_ACTIVITY));
548 } catch (android.content.ActivityNotFoundException e) {
549 Log.e(LOG_TAG, "Couldn't launch music browser", e);
554 final Button homeButton = (Button) findViewById(R.id.home_button);
555 homeButton.setOnClickListener(new View.OnClickListener() {
556 public void onClick(View v) {
558 new Intent(Intent.ACTION_MAIN)
559 .addCategory(Intent.CATEGORY_HOME));
563 final Button nightmodeButton = (Button) findViewById(R.id.nightmode_button);
564 nightmodeButton.setOnClickListener(new View.OnClickListener() {
565 public void onClick(View v) {
571 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
572 public boolean onLongClick(View v) {
580 public void onConfigurationChanged(Configuration newConfig) {
581 super.onConfigurationChanged(newConfig);
582 if (!mScreenSaverMode) {
590 protected void onCreate(Bundle icicle) {
591 super.onCreate(icicle);
596 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
597 } catch (PackageManager.NameNotFoundException e) {
598 // no weather info available
599 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");