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 = true;
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;
137 private boolean mPluggedIn;
139 private PowerManager.WakeLock mWakeLock;
140 private int mIdleTimeoutEpoch = 0;
142 private boolean mWeatherFetchScheduled = false;
148 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
150 public void onReceive(Context context, Intent intent) {
151 final String action = intent.getAction();
152 if (Intent.ACTION_DATE_CHANGED.equals(action)) {
154 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
156 intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
157 intent.getIntExtra("level", 0));
162 private final Handler mHandy = new Handler() {
164 public void handleMessage(Message m) {
165 if (DEBUG) Log.d(LOG_TAG, "handleMessage: " + m.toString());
167 if (m.what == FETCH_WEATHER_DATA_MSG) {
168 if (!mWeatherFetchScheduled) return;
169 mWeatherFetchScheduled = false;
170 new Thread() { public void run() { fetchWeatherData(); } }.start();
171 scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
172 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
173 updateWeatherDisplay();
174 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
175 if (m.arg1 == mIdleTimeoutEpoch) {
178 } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
183 private void moveScreenSaver() {
184 moveScreenSaverTo(-1,-1);
186 private void moveScreenSaverTo(int x, int y) {
187 if (!mScreenSaverMode) return;
189 final View time_date = findViewById(R.id.time_date);
192 final TranslateAnimation anim = new TranslateAnimation(
193 Animation.RELATIVE_TO_SELF, 0, // fromX
194 Animation.RELATIVE_TO_PARENT, 0.5f, // toX
195 Animation.RELATIVE_TO_SELF, 0, // fromY
196 Animation.RELATIVE_TO_PARENT, 0.5f // toY
198 anim.setDuration(1000);
199 anim.setInterpolator(new android.view.animation.AccelerateDecelerateInterpolator());
200 anim.setFillEnabled(true);
201 anim.setFillAfter(true);
202 time_date.startAnimation(anim);
205 DisplayMetrics metrics = new DisplayMetrics();
206 getWindowManager().getDefaultDisplay().getMetrics(metrics);
208 if (x < 0 || y < 0) {
209 int myWidth = time_date.getMeasuredWidth();
210 int myHeight = time_date.getMeasuredHeight();
211 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
212 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
215 time_date.setLayoutParams(new AbsoluteLayout.LayoutParams(
216 ViewGroup.LayoutParams.WRAP_CONTENT,
217 ViewGroup.LayoutParams.WRAP_CONTENT,
221 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG, SCREEN_SAVER_MOVE_DELAY);
224 private void restoreScreen() {
225 if (!mScreenSaverMode) return;
226 mScreenSaverMode = false;
228 doDim(false); // restores previous dim mode
232 // Special screen-saver mode for OLED displays that burn in quickly
233 private void saveScreen() {
234 if (mScreenSaverMode) return;
236 // quickly stash away the x/y of the current date
237 final View oldTimeDate = findViewById(R.id.time_date);
238 int oldLoc[] = new int[2];
239 oldTimeDate.getLocationOnScreen(oldLoc);
241 mScreenSaverMode = true;
242 Window win = getWindow();
243 WindowManager.LayoutParams winParams = win.getAttributes();
244 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
245 win.setAttributes(winParams);
247 setContentView(R.layout.desk_clock_saver);
249 mTime = (DigitalClock) findViewById(R.id.time);
250 mDate = (TextView) findViewById(R.id.date);
252 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
254 ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
255 ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
256 mDate.setTextColor(color);
260 mWeatherHighTemperature =
261 mWeatherLowTemperature =
262 mWeatherLocation = null;
267 moveScreenSaverTo(oldLoc[0], oldLoc[1]);
271 public void onUserInteraction() {
272 if (mScreenSaverMode)
276 private boolean supportsWeather() {
277 return (mGenieResources != null);
280 private void scheduleWeatherFetchDelayed(long delay) {
281 if (mWeatherFetchScheduled) return;
283 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
285 mWeatherFetchScheduled = true;
287 mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
290 private void unscheduleWeatherFetch() {
291 mWeatherFetchScheduled = false;
294 private static final boolean sCelsius;
296 String cc = Locale.getDefault().getCountry().toLowerCase();
297 sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc));
300 private static int celsiusToLocal(int tempC) {
301 return sCelsius ? tempC : (int)(tempC * 1.8f + 32);
304 private void fetchWeatherData() {
305 // if we couldn't load the weather widget's resources, we simply
306 // assume it's not present on the device.
307 if (mGenieResources == null) return;
309 Uri queryUri = new Uri.Builder()
310 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
311 .authority(WEATHER_CONTENT_AUTHORITY)
312 .path(WEATHER_CONTENT_PATH)
313 .appendPath(new Long(System.currentTimeMillis()).toString())
316 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
322 WEATHER_CONTENT_COLUMNS,
326 } catch (RuntimeException e) {
327 Log.e(LOG_TAG, "Weather query failed", e);
331 if (cur != null && cur.moveToFirst()) {
332 mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
333 cur.getColumnIndexOrThrow("iconResId")));
334 mWeatherHighTemperatureString = String.format("%d\u00b0",
335 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
336 mWeatherLowTemperatureString = String.format("%d\u00b0",
337 celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
338 mWeatherLocationString = cur.getString(
339 cur.getColumnIndexOrThrow("location"));
341 Log.w(LOG_TAG, "No weather information available (cur="
343 mWeatherIconDrawable = null;
344 mWeatherHighTemperatureString = "";
345 mWeatherLowTemperatureString = "";
346 mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
349 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
352 private void refreshWeather() {
353 if (supportsWeather())
354 scheduleWeatherFetchDelayed(0);
355 updateWeatherDisplay(); // in case we have it cached
358 private void updateWeatherDisplay() {
359 if (mWeatherHighTemperature == null) return;
361 mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
362 mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
363 mWeatherLocation.setText(mWeatherLocationString);
364 mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
367 // Adapted from KeyguardUpdateMonitor.java
368 private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
369 final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
370 if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
371 mBatteryLevel = batteryLevel;
372 mPluggedIn = pluggedIn;
376 if (!mWakeLock.isHeld()) mWakeLock.acquire();
378 if (mWakeLock.isHeld()) mWakeLock.release();
383 private void refreshBattery() {
384 if (mBatteryDisplay == null) return;
386 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
387 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
388 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
389 mBatteryDisplay.setText(
390 getString(R.string.battery_charging_level, mBatteryLevel));
391 mBatteryDisplay.setVisibility(View.VISIBLE);
393 mBatteryDisplay.setVisibility(View.INVISIBLE);
397 private void refreshDate() {
398 mDate.setText(mDateFormat.format(new Date()));
401 private void refreshAlarm() {
402 if (mNextAlarm == null) return;
404 String nextAlarm = Settings.System.getString(getContentResolver(),
405 Settings.System.NEXT_ALARM_FORMATTED);
406 if (!TextUtils.isEmpty(nextAlarm)) {
407 mNextAlarm.setText(nextAlarm);
408 //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
409 // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
410 mNextAlarm.setVisibility(View.VISIBLE);
412 mNextAlarm.setVisibility(View.INVISIBLE);
416 private void refreshAll() {
423 private void doDim(boolean fade) {
424 View tintView = findViewById(R.id.window_tint);
425 if (tintView == null) return;
427 Window win = getWindow();
428 WindowManager.LayoutParams winParams = win.getAttributes();
430 // dim the wallpaper somewhat (how much is determined below)
431 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
434 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
435 winParams.dimAmount = 0.5f; // pump up contrast in dim mode
437 // show the window tint
438 tintView.startAnimation(AnimationUtils.loadAnimation(this,
440 : R.anim.dim_instant));
442 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
443 winParams.dimAmount = 0.2f; // lower contrast in normal mode
445 // hide the window tint
446 tintView.startAnimation(AnimationUtils.loadAnimation(this,
448 : R.anim.undim_instant));
451 win.setAttributes(winParams);
455 public void onResume() {
458 // reload the date format in case the user has changed settings
460 mDateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
462 IntentFilter filter = new IntentFilter();
463 filter.addAction(Intent.ACTION_DATE_CHANGED);
464 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
465 registerReceiver(mIntentReceiver, filter);
469 if (mPluggedIn && !mWakeLock.isHeld()) mWakeLock.acquire();
472 mHandy.sendMessageDelayed(
473 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0),
474 SCREEN_SAVER_TIMEOUT);
478 public void onPause() {
480 unregisterReceiver(mIntentReceiver);
481 unscheduleWeatherFetch();
482 if (mWakeLock.isHeld()) mWakeLock.release();
486 private void initViews() {
487 setContentView(R.layout.desk_clock);
489 mTime = (DigitalClock) findViewById(R.id.time);
490 mDate = (TextView) findViewById(R.id.date);
491 mBatteryDisplay = (TextView) findViewById(R.id.battery);
493 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
494 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
495 mWeatherLocation = (TextView) findViewById(R.id.weather_location);
496 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
498 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
500 final Button alarmButton = (Button) findViewById(R.id.alarm_button);
501 alarmButton.setOnClickListener(new View.OnClickListener() {
502 public void onClick(View v) {
503 startActivity(new Intent(DeskClock.this, AlarmClock.class));
507 final Button galleryButton = (Button) findViewById(R.id.gallery_button);
508 galleryButton.setOnClickListener(new View.OnClickListener() {
509 public void onClick(View v) {
511 startActivity(new Intent(
513 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
514 } catch (android.content.ActivityNotFoundException e) {
515 Log.e(LOG_TAG, "Couldn't launch image browser", e);
520 final Button musicButton = (Button) findViewById(R.id.music_button);
521 musicButton.setOnClickListener(new View.OnClickListener() {
522 public void onClick(View v) {
524 startActivity(new Intent(MUSIC_NOW_PLAYING_ACTIVITY));
525 } catch (android.content.ActivityNotFoundException e) {
526 Log.e(LOG_TAG, "Couldn't launch music browser", e);
531 final Button homeButton = (Button) findViewById(R.id.home_button);
532 homeButton.setOnClickListener(new View.OnClickListener() {
533 public void onClick(View v) {
535 new Intent(Intent.ACTION_MAIN)
536 .addCategory(Intent.CATEGORY_HOME));
540 final Button nightmodeButton = (Button) findViewById(R.id.nightmode_button);
541 nightmodeButton.setOnClickListener(new View.OnClickListener() {
542 public void onClick(View v) {
548 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
549 public boolean onLongClick(View v) {
557 public void onConfigurationChanged(Configuration newConfig) {
558 super.onConfigurationChanged(newConfig);
559 if (!mScreenSaverMode) {
567 protected void onCreate(Bundle icicle) {
568 super.onCreate(icicle);
570 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
571 mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
578 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
579 } catch (PackageManager.NameNotFoundException e) {
580 // no weather info available
581 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");