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.AlarmManager;
21 import android.app.AlertDialog;
22 import android.app.PendingIntent;
23 import android.content.BroadcastReceiver;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.content.Intent;
27 import android.content.IntentFilter;
28 import android.content.SharedPreferences;
29 import android.content.pm.PackageManager;
30 import android.content.res.Configuration;
31 import android.content.res.Resources;
32 import android.database.ContentObserver;
33 import android.database.Cursor;
34 import android.graphics.Rect;
35 import android.graphics.drawable.BitmapDrawable;
36 import android.graphics.drawable.ColorDrawable;
37 import android.graphics.drawable.Drawable;
38 import android.net.Uri;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.Message;
42 import android.os.SystemClock;
43 import android.os.PowerManager;
44 import android.provider.Settings;
45 import android.text.TextUtils;
46 import android.text.format.DateFormat;
47 import android.util.DisplayMetrics;
48 import android.util.Log;
49 import android.view.ContextMenu.ContextMenuInfo;
50 import android.view.ContextMenu;
51 import android.view.LayoutInflater;
52 import android.view.Menu;
53 import android.view.MenuInflater;
54 import android.view.MenuItem;
55 import android.view.MotionEvent;
56 import android.view.View.OnClickListener;
57 import android.view.View.OnCreateContextMenuListener;
58 import android.view.View;
59 import android.view.ViewGroup;
60 import android.view.ViewTreeObserver;
61 import android.view.ViewTreeObserver.OnGlobalFocusChangeListener;
62 import android.view.Window;
63 import android.view.WindowManager;
64 import android.view.animation.Animation;
65 import android.view.animation.AnimationUtils;
66 import android.view.animation.TranslateAnimation;
67 import android.widget.AbsoluteLayout;
68 import android.widget.AdapterView.AdapterContextMenuInfo;
69 import android.widget.AdapterView.OnItemClickListener;
70 import android.widget.AdapterView;
71 import android.widget.Button;
72 import android.widget.CheckBox;
73 import android.widget.ImageButton;
74 import android.widget.ImageView;
75 import android.widget.TextView;
77 import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
78 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
79 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
81 import java.io.IOException;
82 import java.io.InputStream;
83 import java.util.Calendar;
84 import java.util.Date;
85 import java.util.Locale;
86 import java.util.Random;
89 * DeskClock clock view for desk docks.
91 public class DeskClock extends Activity {
92 private static final boolean DEBUG = false;
94 private static final String LOG_TAG = "DeskClock";
96 // Package ID of the music player.
97 private static final String MUSIC_PACKAGE_ID = "com.android.music";
99 // Alarm action for midnight (so we can update the date display).
100 private static final String ACTION_MIDNIGHT = "com.android.deskclock.MIDNIGHT";
102 // Interval between forced polls of the weather widget.
103 private final long QUERY_WEATHER_DELAY = 60 * 60 * 1000; // 1 hr
105 // Intent to broadcast for dock settings.
106 private static final String DOCK_SETTINGS_ACTION = "com.android.settings.DOCK_SETTINGS";
108 // Delay before engaging the burn-in protection mode (green-on-black).
109 private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min
111 // Repositioning delay in screen saver.
112 private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
114 // Color to use for text & graphics in screen saver mode.
115 private final int SCREEN_SAVER_COLOR = 0xFF308030;
116 private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018;
118 // Opacity of black layer between clock display and wallpaper.
119 private final float DIM_BEHIND_AMOUNT_NORMAL = 0.4f;
120 private final float DIM_BEHIND_AMOUNT_DIMMED = 0.8f; // higher contrast when display dimmed
122 // Internal message IDs.
123 private final int QUERY_WEATHER_DATA_MSG = 0x1000;
124 private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
125 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000;
126 private final int SCREEN_SAVER_MOVE_MSG = 0x2001;
128 // Weather widget query information.
129 private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
130 private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
131 private static final String WEATHER_CONTENT_PATH = "/weather/current";
132 private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
143 private static final String ACTION_GENIE_REFRESH = "com.google.android.apps.genie.REFRESH";
145 // State variables follow.
146 private DigitalClock mTime;
147 private TextView mDate;
149 private TextView mNextAlarm = null;
150 private TextView mBatteryDisplay;
152 private TextView mWeatherCurrentTemperature;
153 private TextView mWeatherHighTemperature;
154 private TextView mWeatherLowTemperature;
155 private TextView mWeatherLocation;
156 private ImageView mWeatherIcon;
158 private String mWeatherCurrentTemperatureString;
159 private String mWeatherHighTemperatureString;
160 private String mWeatherLowTemperatureString;
161 private String mWeatherLocationString;
162 private Drawable mWeatherIconDrawable;
164 private Resources mGenieResources = null;
166 private boolean mDimmed = false;
167 private boolean mScreenSaverMode = false;
169 private String mDateFormat;
171 private int mBatteryLevel = -1;
172 private boolean mPluggedIn = false;
174 private boolean mLaunchedFromDock = false;
178 private PendingIntent mMidnightIntent;
180 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
182 public void onReceive(Context context, Intent intent) {
183 final String action = intent.getAction();
184 if (DEBUG) Log.d(LOG_TAG, "mIntentReceiver.onReceive: action=" + action + ", intent=" + intent);
185 if (Intent.ACTION_DATE_CHANGED.equals(action) || ACTION_MIDNIGHT.equals(action)) {
187 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
189 intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
190 intent.getIntExtra("level", 0));
191 } else if (Intent.ACTION_DOCK_EVENT.equals(action)) {
192 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, -1);
193 if (DEBUG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT, state=" + state);
194 if (state == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
195 if (mLaunchedFromDock) {
196 // moveTaskToBack(false);
199 mLaunchedFromDock = false;
205 private final Handler mHandy = new Handler() {
207 public void handleMessage(Message m) {
208 if (m.what == QUERY_WEATHER_DATA_MSG) {
209 new Thread() { public void run() { queryWeatherData(); } }.start();
210 scheduleWeatherQueryDelayed(QUERY_WEATHER_DELAY);
211 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
212 updateWeatherDisplay();
213 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
215 } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
221 private final ContentObserver mContentObserver = new ContentObserver(mHandy) {
223 public void onChange(boolean selfChange) {
224 if (DEBUG) Log.d(LOG_TAG, "content observer notified that weather changed");
230 private void moveScreenSaver() {
231 moveScreenSaverTo(-1,-1);
233 private void moveScreenSaverTo(int x, int y) {
234 if (!mScreenSaverMode) return;
236 final View saver_view = findViewById(R.id.saver_view);
238 DisplayMetrics metrics = new DisplayMetrics();
239 getWindowManager().getDefaultDisplay().getMetrics(metrics);
241 if (x < 0 || y < 0) {
242 int myWidth = saver_view.getMeasuredWidth();
243 int myHeight = saver_view.getMeasuredHeight();
244 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
245 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
248 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
249 System.currentTimeMillis(), x, y));
251 saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams(
252 ViewGroup.LayoutParams.WRAP_CONTENT,
253 ViewGroup.LayoutParams.WRAP_CONTENT,
257 // Synchronize our jumping so that it happens exactly on the second.
258 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
259 SCREEN_SAVER_MOVE_DELAY +
260 (1000 - (System.currentTimeMillis() % 1000)));
263 private void setWakeLock(boolean hold) {
264 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
265 Window win = getWindow();
266 WindowManager.LayoutParams winParams = win.getAttributes();
267 winParams.flags |= (WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
268 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
269 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
270 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
272 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
274 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
275 win.setAttributes(winParams);
278 private void scheduleScreenSaver() {
279 // reschedule screen saver
280 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
281 mHandy.sendMessageDelayed(
282 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG),
283 SCREEN_SAVER_TIMEOUT);
286 private void restoreScreen() {
287 if (!mScreenSaverMode) return;
288 if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
289 mScreenSaverMode = false;
291 doDim(false); // restores previous dim mode
292 // policy: update weather info when returning from screen saver
293 if (mPluggedIn) requestWeatherDataFetch();
295 scheduleScreenSaver();
300 // Special screen-saver mode for OLED displays that burn in quickly
301 private void saveScreen() {
302 if (mScreenSaverMode) return;
303 if (DEBUG) Log.d(LOG_TAG, "saveScreen");
305 // quickly stash away the x/y of the current date
306 final View oldTimeDate = findViewById(R.id.time_date);
307 int oldLoc[] = new int[2];
308 oldTimeDate.getLocationOnScreen(oldLoc);
310 mScreenSaverMode = true;
311 Window win = getWindow();
312 WindowManager.LayoutParams winParams = win.getAttributes();
313 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
314 win.setAttributes(winParams);
316 // give up any internal focus before we switch layouts
317 final View focused = getCurrentFocus();
318 if (focused != null) focused.clearFocus();
320 setContentView(R.layout.desk_clock_saver);
322 mTime = (DigitalClock) findViewById(R.id.time);
323 mDate = (TextView) findViewById(R.id.date);
324 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
326 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
328 ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
329 ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
330 mDate.setTextColor(color);
331 mNextAlarm.setTextColor(color);
332 mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
333 getResources().getDrawable(mDimmed
334 ? R.drawable.ic_lock_idle_alarm_saver_dim
335 : R.drawable.ic_lock_idle_alarm_saver),
339 mWeatherCurrentTemperature =
340 mWeatherHighTemperature =
341 mWeatherLowTemperature =
342 mWeatherLocation = null;
348 moveScreenSaverTo(oldLoc[0], oldLoc[1]);
352 public void onUserInteraction() {
353 if (mScreenSaverMode)
357 // Tell the Genie widget to load new data from the network.
358 private void requestWeatherDataFetch() {
359 if (DEBUG) Log.d(LOG_TAG, "forcing the Genie widget to update weather now...");
360 sendBroadcast(new Intent(ACTION_GENIE_REFRESH).putExtra("requestWeather", true));
361 // we expect the result to show up in our content observer
364 private boolean supportsWeather() {
365 return (mGenieResources != null);
368 private void scheduleWeatherQueryDelayed(long delay) {
369 // cancel any existing scheduled queries
370 unscheduleWeatherQuery();
372 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
374 mHandy.sendEmptyMessageDelayed(QUERY_WEATHER_DATA_MSG, delay);
377 private void unscheduleWeatherQuery() {
378 mHandy.removeMessages(QUERY_WEATHER_DATA_MSG);
381 private void queryWeatherData() {
382 // if we couldn't load the weather widget's resources, we simply
383 // assume it's not present on the device.
384 if (mGenieResources == null) return;
386 Uri queryUri = new Uri.Builder()
387 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
388 .authority(WEATHER_CONTENT_AUTHORITY)
389 .path(WEATHER_CONTENT_PATH)
390 .appendPath(new Long(System.currentTimeMillis()).toString())
393 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
399 WEATHER_CONTENT_COLUMNS,
403 } catch (RuntimeException e) {
404 Log.e(LOG_TAG, "Weather query failed", e);
408 if (cur != null && cur.moveToFirst()) {
410 java.lang.StringBuilder sb =
411 new java.lang.StringBuilder("Weather query result: {");
412 for(int i=0; i<cur.getColumnCount(); i++) {
413 if (i>0) sb.append(", ");
414 sb.append(cur.getColumnName(i))
416 .append(cur.getString(i));
419 Log.d(LOG_TAG, sb.toString());
422 mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
423 cur.getColumnIndexOrThrow("iconResId")));
424 mWeatherCurrentTemperatureString = String.format("%d\u00b0",
425 (cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
426 mWeatherHighTemperatureString = String.format("%d\u00b0",
427 (cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
428 mWeatherLowTemperatureString = String.format("%d\u00b0",
429 (cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
430 mWeatherLocationString = cur.getString(
431 cur.getColumnIndexOrThrow("location"));
433 Log.w(LOG_TAG, "No weather information available (cur="
435 mWeatherIconDrawable = null;
436 mWeatherHighTemperatureString = "";
437 mWeatherLowTemperatureString = "";
438 mWeatherLocationString = getString(R.string.weather_fetch_failure);
441 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
444 private void refreshWeather() {
445 if (supportsWeather())
446 scheduleWeatherQueryDelayed(0);
447 updateWeatherDisplay(); // in case we have it cached
450 private void updateWeatherDisplay() {
451 if (mWeatherCurrentTemperature == null) return;
453 mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
454 mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
455 mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
456 mWeatherLocation.setText(mWeatherLocationString);
457 mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
460 // Adapted from KeyguardUpdateMonitor.java
461 private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
462 final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
463 if (pluggedIn != mPluggedIn) {
464 setWakeLock(pluggedIn);
467 // policy: update weather info when attaching to power
468 requestWeatherDataFetch();
471 if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
472 mBatteryLevel = batteryLevel;
473 mPluggedIn = pluggedIn;
478 private void refreshBattery() {
479 if (mBatteryDisplay == null) return;
481 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
482 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
483 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
484 mBatteryDisplay.setText(
485 getString(R.string.battery_charging_level, mBatteryLevel));
486 mBatteryDisplay.setVisibility(View.VISIBLE);
488 mBatteryDisplay.setVisibility(View.INVISIBLE);
492 private void refreshDate() {
493 final Date now = new Date();
494 if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
495 mDate.setText(DateFormat.format(mDateFormat, now));
498 private void refreshAlarm() {
499 if (mNextAlarm == null) return;
501 String nextAlarm = Settings.System.getString(getContentResolver(),
502 Settings.System.NEXT_ALARM_FORMATTED);
503 if (!TextUtils.isEmpty(nextAlarm)) {
504 mNextAlarm.setText(nextAlarm);
505 //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
506 // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
507 mNextAlarm.setVisibility(View.VISIBLE);
509 mNextAlarm.setVisibility(View.INVISIBLE);
513 private void refreshAll() {
520 private void doDim(boolean fade) {
521 View tintView = findViewById(R.id.window_tint);
522 if (tintView == null) return;
524 Window win = getWindow();
525 WindowManager.LayoutParams winParams = win.getAttributes();
527 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
528 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
530 // dim the wallpaper somewhat (how much is determined below)
531 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
534 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
535 winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED;
536 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
538 // show the window tint
539 tintView.startAnimation(AnimationUtils.loadAnimation(this,
541 : R.anim.dim_instant));
543 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
544 winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL;
545 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
547 // hide the window tint
548 tintView.startAnimation(AnimationUtils.loadAnimation(this,
550 : R.anim.undim_instant));
553 win.setAttributes(winParams);
557 public void onNewIntent(Intent newIntent) {
558 super.onNewIntent(newIntent);
559 if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
561 // update our intent so that we can consult it to determine whether or
562 // not the most recent launch was via a dock event
563 setIntent(newIntent);
567 public void onResume() {
569 if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent());
571 // reload the date format in case the user has changed settings
573 mDateFormat = getString(R.string.full_wday_month_day_no_year);
575 IntentFilter filter = new IntentFilter();
576 filter.addAction(Intent.ACTION_DATE_CHANGED);
577 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
578 filter.addAction(Intent.ACTION_DOCK_EVENT);
579 filter.addAction(ACTION_MIDNIGHT);
580 registerReceiver(mIntentReceiver, filter);
582 // Listen for updates to weather data
583 Uri weatherNotificationUri = new Uri.Builder()
584 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
585 .authority(WEATHER_CONTENT_AUTHORITY)
586 .path(WEATHER_CONTENT_PATH)
588 getContentResolver().registerContentObserver(
589 weatherNotificationUri, true, mContentObserver);
591 // Elaborate mechanism to find out when the day rolls over
592 Calendar today = Calendar.getInstance();
593 today.set(Calendar.HOUR_OF_DAY, 0);
594 today.set(Calendar.MINUTE, 0);
595 today.set(Calendar.SECOND, 0);
596 today.add(Calendar.DATE, 1);
597 long alarmTimeUTC = today.getTimeInMillis() + today.get(Calendar.ZONE_OFFSET);
598 mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
599 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
600 am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent);
601 if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at "
602 + alarmTimeUTC + " repeating every "
603 + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent);
605 // If we weren't previously visible but now we are, it's because we're
606 // being started from another activity. So it's OK to un-dim.
607 if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) {
611 // Adjust the display to reflect the currently chosen dim mode.
614 restoreScreen(); // disable screen saver
615 refreshAll(); // will schedule periodic weather fetch
617 setWakeLock(mPluggedIn);
619 scheduleScreenSaver();
621 final boolean launchedFromDock
622 = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
624 if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) {
625 // policy: fetch weather if launched via dock connection
626 if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
627 requestWeatherDataFetch();
630 mLaunchedFromDock = launchedFromDock;
634 public void onPause() {
635 if (DEBUG) Log.d(LOG_TAG, "onPause");
637 // Turn off the screen saver and cancel any pending timeouts.
638 // (But don't un-dim.)
639 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
642 // Other things we don't want to be doing in the background.
643 unregisterReceiver(mIntentReceiver);
644 getContentResolver().unregisterContentObserver(mContentObserver);
646 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
647 am.cancel(mMidnightIntent);
648 unscheduleWeatherQuery();
653 private void initViews() {
654 // give up any internal focus before we switch layouts
655 final View focused = getCurrentFocus();
656 if (focused != null) focused.clearFocus();
658 setContentView(R.layout.desk_clock);
660 mTime = (DigitalClock) findViewById(R.id.time);
661 mDate = (TextView) findViewById(R.id.date);
662 mBatteryDisplay = (TextView) findViewById(R.id.battery);
664 mTime.getRootView().requestFocus();
666 mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
667 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
668 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
669 mWeatherLocation = (TextView) findViewById(R.id.weather_location);
670 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
672 final View.OnClickListener alarmClickListener = new View.OnClickListener() {
673 public void onClick(View v) {
674 startActivity(new Intent(DeskClock.this, AlarmClock.class));
678 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
679 mNextAlarm.setOnClickListener(alarmClickListener);
681 final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
682 alarmButton.setOnClickListener(alarmClickListener);
684 final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
685 galleryButton.setOnClickListener(new View.OnClickListener() {
686 public void onClick(View v) {
688 startActivity(new Intent(
690 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
691 .putExtra("slideshow", true)
692 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
693 } catch (android.content.ActivityNotFoundException e) {
694 Log.e(LOG_TAG, "Couldn't launch image browser", e);
699 final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
700 musicButton.setOnClickListener(new View.OnClickListener() {
701 public void onClick(View v) {
703 Intent musicAppQuery = getPackageManager()
704 .getLaunchIntentForPackage(MUSIC_PACKAGE_ID);
705 if (musicAppQuery != null) {
706 musicAppQuery.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
707 startActivity(musicAppQuery);
709 } catch (android.content.ActivityNotFoundException e) {
710 Log.e(LOG_TAG, "Couldn't launch music browser", e);
715 final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
716 homeButton.setOnClickListener(new View.OnClickListener() {
717 public void onClick(View v) {
719 new Intent(Intent.ACTION_MAIN)
720 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)
721 .addCategory(Intent.CATEGORY_HOME));
725 final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
726 nightmodeButton.setOnClickListener(new View.OnClickListener() {
727 public void onClick(View v) {
733 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
734 public boolean onLongClick(View v) {
740 final View weatherView = findViewById(R.id.weather);
741 weatherView.setOnClickListener(new View.OnClickListener() {
742 public void onClick(View v) {
743 if (!supportsWeather()) return;
745 Intent genieAppQuery = getPackageManager()
746 .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
747 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
748 if (genieAppQuery != null) {
749 startActivity(genieAppQuery);
754 final View tintView = findViewById(R.id.window_tint);
755 tintView.setOnTouchListener(new View.OnTouchListener() {
756 public boolean onTouch(View v, MotionEvent event) {
757 if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) {
758 // We want to un-dim the whole screen on tap.
759 // ...Unless the user is specifically tapping on the dim
760 // widget, in which case let it do the work.
762 nightmodeButton.getHitRect(r);
763 int[] gloc = new int[2];
764 nightmodeButton.getLocationInWindow(gloc);
765 r.offsetTo(gloc[0], gloc[1]); // convert to window coords
767 if (!r.contains((int) event.getX(), (int) event.getY())) {
772 return false; // always pass the click through
776 // Tidy up awkward focus behavior: the first view to be focused in
777 // trackball mode should be the alarms button
778 final ViewTreeObserver vto = alarmButton.getViewTreeObserver();
779 vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
780 public void onGlobalFocusChanged(View oldFocus, View newFocus) {
781 if (oldFocus == null && newFocus == nightmodeButton) {
782 alarmButton.requestFocus();
789 public void onConfigurationChanged(Configuration newConfig) {
790 super.onConfigurationChanged(newConfig);
791 if (mScreenSaverMode) {
801 public boolean onOptionsItemSelected(MenuItem item) {
802 switch (item.getItemId()) {
803 case R.id.menu_item_alarms:
804 startActivity(new Intent(DeskClock.this, AlarmClock.class));
806 case R.id.menu_item_add_alarm:
807 startActivity(new Intent(this, SetAlarm.class));
809 case R.id.menu_item_dock_settings:
810 startActivity(new Intent(DOCK_SETTINGS_ACTION));
818 public boolean onCreateOptionsMenu(Menu menu) {
819 MenuInflater inflater = getMenuInflater();
820 inflater.inflate(R.menu.desk_clock_menu, menu);
825 protected void onCreate(Bundle icicle) {
826 super.onCreate(icicle);
831 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
832 } catch (PackageManager.NameNotFoundException e) {
833 // no weather info available
834 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");