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.provider.MediaStore;
46 import android.text.TextUtils;
47 import android.text.format.DateFormat;
48 import android.util.DisplayMetrics;
49 import android.util.Log;
50 import android.view.ContextMenu.ContextMenuInfo;
51 import android.view.ContextMenu;
52 import android.view.LayoutInflater;
53 import android.view.Menu;
54 import android.view.MenuInflater;
55 import android.view.MenuItem;
56 import android.view.MotionEvent;
57 import android.view.View.OnClickListener;
58 import android.view.View.OnCreateContextMenuListener;
59 import android.view.View;
60 import android.view.ViewGroup;
61 import android.view.ViewTreeObserver;
62 import android.view.ViewTreeObserver.OnGlobalFocusChangeListener;
63 import android.view.Window;
64 import android.view.WindowManager;
65 import android.view.animation.Animation;
66 import android.view.animation.AnimationUtils;
67 import android.view.animation.TranslateAnimation;
68 import android.widget.AbsoluteLayout;
69 import android.widget.AdapterView.AdapterContextMenuInfo;
70 import android.widget.AdapterView.OnItemClickListener;
71 import android.widget.AdapterView;
72 import android.widget.Button;
73 import android.widget.CheckBox;
74 import android.widget.ImageButton;
75 import android.widget.ImageView;
76 import android.widget.TextView;
78 import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
79 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
80 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
82 import java.io.IOException;
83 import java.io.InputStream;
84 import java.util.Calendar;
85 import java.util.Date;
86 import java.util.Locale;
87 import java.util.Random;
90 * DeskClock clock view for desk docks.
92 public class DeskClock extends Activity {
93 private static final boolean DEBUG = false;
95 private static final String LOG_TAG = "DeskClock";
97 // Alarm action for midnight (so we can update the date display).
98 private static final String ACTION_MIDNIGHT = "com.android.deskclock.MIDNIGHT";
100 // Interval between forced polls of the weather widget.
101 private final long QUERY_WEATHER_DELAY = 60 * 60 * 1000; // 1 hr
103 // Intent to broadcast for dock settings.
104 private static final String DOCK_SETTINGS_ACTION = "com.android.settings.DOCK_SETTINGS";
106 // Delay before engaging the burn-in protection mode (green-on-black).
107 private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min
109 // Repositioning delay in screen saver.
110 private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
112 // Color to use for text & graphics in screen saver mode.
113 private final int SCREEN_SAVER_COLOR = 0xFF308030;
114 private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018;
116 // Opacity of black layer between clock display and wallpaper.
117 private final float DIM_BEHIND_AMOUNT_NORMAL = 0.4f;
118 private final float DIM_BEHIND_AMOUNT_DIMMED = 0.8f; // higher contrast when display dimmed
120 // Internal message IDs.
121 private final int QUERY_WEATHER_DATA_MSG = 0x1000;
122 private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
123 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000;
124 private final int SCREEN_SAVER_MOVE_MSG = 0x2001;
126 // Weather widget query information.
127 private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
128 private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
129 private static final String WEATHER_CONTENT_PATH = "/weather/current";
130 private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
141 private static final String ACTION_GENIE_REFRESH = "com.google.android.apps.genie.REFRESH";
143 // State variables follow.
144 private DigitalClock mTime;
145 private TextView mDate;
147 private TextView mNextAlarm = null;
148 private TextView mBatteryDisplay;
150 private TextView mWeatherCurrentTemperature;
151 private TextView mWeatherHighTemperature;
152 private TextView mWeatherLowTemperature;
153 private TextView mWeatherLocation;
154 private ImageView mWeatherIcon;
156 private String mWeatherCurrentTemperatureString;
157 private String mWeatherHighTemperatureString;
158 private String mWeatherLowTemperatureString;
159 private String mWeatherLocationString;
160 private Drawable mWeatherIconDrawable;
162 private Resources mGenieResources = null;
164 private boolean mDimmed = false;
165 private boolean mScreenSaverMode = false;
167 private String mDateFormat;
169 private int mBatteryLevel = -1;
170 private boolean mPluggedIn = false;
172 private boolean mLaunchedFromDock = false;
176 private PendingIntent mMidnightIntent;
178 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
180 public void onReceive(Context context, Intent intent) {
181 final String action = intent.getAction();
182 if (DEBUG) Log.d(LOG_TAG, "mIntentReceiver.onReceive: action=" + action + ", intent=" + intent);
183 if (Intent.ACTION_DATE_CHANGED.equals(action) || ACTION_MIDNIGHT.equals(action)) {
185 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
187 intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
188 intent.getIntExtra("level", 0));
189 } else if (Intent.ACTION_DOCK_EVENT.equals(action)) {
190 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, -1);
191 if (DEBUG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT, state=" + state);
192 if (state == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
193 if (mLaunchedFromDock) {
194 // moveTaskToBack(false);
197 mLaunchedFromDock = false;
203 private final Handler mHandy = new Handler() {
205 public void handleMessage(Message m) {
206 if (m.what == QUERY_WEATHER_DATA_MSG) {
207 new Thread() { public void run() { queryWeatherData(); } }.start();
208 scheduleWeatherQueryDelayed(QUERY_WEATHER_DELAY);
209 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
210 updateWeatherDisplay();
211 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
213 } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
219 private final ContentObserver mContentObserver = new ContentObserver(mHandy) {
221 public void onChange(boolean selfChange) {
222 if (DEBUG) Log.d(LOG_TAG, "content observer notified that weather changed");
228 private void moveScreenSaver() {
229 moveScreenSaverTo(-1,-1);
231 private void moveScreenSaverTo(int x, int y) {
232 if (!mScreenSaverMode) return;
234 final View saver_view = findViewById(R.id.saver_view);
236 DisplayMetrics metrics = new DisplayMetrics();
237 getWindowManager().getDefaultDisplay().getMetrics(metrics);
239 if (x < 0 || y < 0) {
240 int myWidth = saver_view.getMeasuredWidth();
241 int myHeight = saver_view.getMeasuredHeight();
242 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
243 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
246 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
247 System.currentTimeMillis(), x, y));
249 saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams(
250 ViewGroup.LayoutParams.WRAP_CONTENT,
251 ViewGroup.LayoutParams.WRAP_CONTENT,
255 // Synchronize our jumping so that it happens exactly on the second.
256 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
257 SCREEN_SAVER_MOVE_DELAY +
258 (1000 - (System.currentTimeMillis() % 1000)));
261 private void setWakeLock(boolean hold) {
262 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
263 Window win = getWindow();
264 WindowManager.LayoutParams winParams = win.getAttributes();
265 winParams.flags |= (WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
266 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
267 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
268 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
270 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
272 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
273 win.setAttributes(winParams);
276 private void scheduleScreenSaver() {
277 // reschedule screen saver
278 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
279 mHandy.sendMessageDelayed(
280 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG),
281 SCREEN_SAVER_TIMEOUT);
284 private void restoreScreen() {
285 if (!mScreenSaverMode) return;
286 if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
287 mScreenSaverMode = false;
289 doDim(false); // restores previous dim mode
290 // policy: update weather info when returning from screen saver
291 if (mPluggedIn) requestWeatherDataFetch();
293 scheduleScreenSaver();
298 // Special screen-saver mode for OLED displays that burn in quickly
299 private void saveScreen() {
300 if (mScreenSaverMode) return;
301 if (DEBUG) Log.d(LOG_TAG, "saveScreen");
303 // quickly stash away the x/y of the current date
304 final View oldTimeDate = findViewById(R.id.time_date);
305 int oldLoc[] = new int[2];
306 oldTimeDate.getLocationOnScreen(oldLoc);
308 mScreenSaverMode = true;
309 Window win = getWindow();
310 WindowManager.LayoutParams winParams = win.getAttributes();
311 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
312 win.setAttributes(winParams);
314 // give up any internal focus before we switch layouts
315 final View focused = getCurrentFocus();
316 if (focused != null) focused.clearFocus();
318 setContentView(R.layout.desk_clock_saver);
320 mTime = (DigitalClock) findViewById(R.id.time);
321 mDate = (TextView) findViewById(R.id.date);
322 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
324 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
326 ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
327 ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
328 mDate.setTextColor(color);
329 mNextAlarm.setTextColor(color);
330 mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
331 getResources().getDrawable(mDimmed
332 ? R.drawable.ic_lock_idle_alarm_saver_dim
333 : R.drawable.ic_lock_idle_alarm_saver),
337 mWeatherCurrentTemperature =
338 mWeatherHighTemperature =
339 mWeatherLowTemperature =
340 mWeatherLocation = null;
346 moveScreenSaverTo(oldLoc[0], oldLoc[1]);
350 public void onUserInteraction() {
351 if (mScreenSaverMode)
355 // Tell the Genie widget to load new data from the network.
356 private void requestWeatherDataFetch() {
357 if (DEBUG) Log.d(LOG_TAG, "forcing the Genie widget to update weather now...");
358 sendBroadcast(new Intent(ACTION_GENIE_REFRESH).putExtra("requestWeather", true));
359 // we expect the result to show up in our content observer
362 private boolean supportsWeather() {
363 return (mGenieResources != null);
366 private void scheduleWeatherQueryDelayed(long delay) {
367 // cancel any existing scheduled queries
368 unscheduleWeatherQuery();
370 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
372 mHandy.sendEmptyMessageDelayed(QUERY_WEATHER_DATA_MSG, delay);
375 private void unscheduleWeatherQuery() {
376 mHandy.removeMessages(QUERY_WEATHER_DATA_MSG);
379 private void queryWeatherData() {
380 // if we couldn't load the weather widget's resources, we simply
381 // assume it's not present on the device.
382 if (mGenieResources == null) return;
384 Uri queryUri = new Uri.Builder()
385 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
386 .authority(WEATHER_CONTENT_AUTHORITY)
387 .path(WEATHER_CONTENT_PATH)
388 .appendPath(new Long(System.currentTimeMillis()).toString())
391 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
397 WEATHER_CONTENT_COLUMNS,
401 } catch (RuntimeException e) {
402 Log.e(LOG_TAG, "Weather query failed", e);
406 if (cur != null && cur.moveToFirst()) {
408 java.lang.StringBuilder sb =
409 new java.lang.StringBuilder("Weather query result: {");
410 for(int i=0; i<cur.getColumnCount(); i++) {
411 if (i>0) sb.append(", ");
412 sb.append(cur.getColumnName(i))
414 .append(cur.getString(i));
417 Log.d(LOG_TAG, sb.toString());
420 mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
421 cur.getColumnIndexOrThrow("iconResId")));
422 mWeatherCurrentTemperatureString = String.format("%d\u00b0",
423 (cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
424 mWeatherHighTemperatureString = String.format("%d\u00b0",
425 (cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
426 mWeatherLowTemperatureString = String.format("%d\u00b0",
427 (cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
428 mWeatherLocationString = cur.getString(
429 cur.getColumnIndexOrThrow("location"));
431 Log.w(LOG_TAG, "No weather information available (cur="
433 mWeatherIconDrawable = null;
434 mWeatherHighTemperatureString = "";
435 mWeatherLowTemperatureString = "";
436 mWeatherLocationString = getString(R.string.weather_fetch_failure);
439 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
442 private void refreshWeather() {
443 if (supportsWeather())
444 scheduleWeatherQueryDelayed(0);
445 updateWeatherDisplay(); // in case we have it cached
448 private void updateWeatherDisplay() {
449 if (mWeatherCurrentTemperature == null) return;
451 mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
452 mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
453 mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
454 mWeatherLocation.setText(mWeatherLocationString);
455 mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
458 // Adapted from KeyguardUpdateMonitor.java
459 private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
460 final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
461 if (pluggedIn != mPluggedIn) {
462 setWakeLock(pluggedIn);
465 // policy: update weather info when attaching to power
466 requestWeatherDataFetch();
469 if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
470 mBatteryLevel = batteryLevel;
471 mPluggedIn = pluggedIn;
476 private void refreshBattery() {
477 if (mBatteryDisplay == null) return;
479 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
480 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
481 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
482 mBatteryDisplay.setText(
483 getString(R.string.battery_charging_level, mBatteryLevel));
484 mBatteryDisplay.setVisibility(View.VISIBLE);
486 mBatteryDisplay.setVisibility(View.INVISIBLE);
490 private void refreshDate() {
491 final Date now = new Date();
492 if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
493 mDate.setText(DateFormat.format(mDateFormat, now));
496 private void refreshAlarm() {
497 if (mNextAlarm == null) return;
499 String nextAlarm = Settings.System.getString(getContentResolver(),
500 Settings.System.NEXT_ALARM_FORMATTED);
501 if (!TextUtils.isEmpty(nextAlarm)) {
502 mNextAlarm.setText(nextAlarm);
503 //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
504 // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
505 mNextAlarm.setVisibility(View.VISIBLE);
507 mNextAlarm.setVisibility(View.INVISIBLE);
511 private void refreshAll() {
518 private void doDim(boolean fade) {
519 View tintView = findViewById(R.id.window_tint);
520 if (tintView == null) return;
522 Window win = getWindow();
523 WindowManager.LayoutParams winParams = win.getAttributes();
525 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
526 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
528 // dim the wallpaper somewhat (how much is determined below)
529 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
532 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
533 winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED;
534 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
536 // show the window tint
537 tintView.startAnimation(AnimationUtils.loadAnimation(this,
539 : R.anim.dim_instant));
541 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
542 winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL;
543 winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
545 // hide the window tint
546 tintView.startAnimation(AnimationUtils.loadAnimation(this,
548 : R.anim.undim_instant));
551 win.setAttributes(winParams);
555 public void onNewIntent(Intent newIntent) {
556 super.onNewIntent(newIntent);
557 if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
559 // update our intent so that we can consult it to determine whether or
560 // not the most recent launch was via a dock event
561 setIntent(newIntent);
565 public void onResume() {
567 if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent());
569 // reload the date format in case the user has changed settings
571 mDateFormat = getString(R.string.full_wday_month_day_no_year);
573 IntentFilter filter = new IntentFilter();
574 filter.addAction(Intent.ACTION_DATE_CHANGED);
575 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
576 filter.addAction(Intent.ACTION_DOCK_EVENT);
577 filter.addAction(ACTION_MIDNIGHT);
578 registerReceiver(mIntentReceiver, filter);
580 // Listen for updates to weather data
581 Uri weatherNotificationUri = new Uri.Builder()
582 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
583 .authority(WEATHER_CONTENT_AUTHORITY)
584 .path(WEATHER_CONTENT_PATH)
586 getContentResolver().registerContentObserver(
587 weatherNotificationUri, true, mContentObserver);
589 // Elaborate mechanism to find out when the day rolls over
590 Calendar today = Calendar.getInstance();
591 today.set(Calendar.HOUR_OF_DAY, 0);
592 today.set(Calendar.MINUTE, 0);
593 today.set(Calendar.SECOND, 0);
594 today.add(Calendar.DATE, 1);
595 long alarmTimeUTC = today.getTimeInMillis() + today.get(Calendar.ZONE_OFFSET);
596 mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
597 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
598 am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent);
599 if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at "
600 + alarmTimeUTC + " repeating every "
601 + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent);
603 // If we weren't previously visible but now we are, it's because we're
604 // being started from another activity. So it's OK to un-dim.
605 if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) {
609 // Adjust the display to reflect the currently chosen dim mode.
612 restoreScreen(); // disable screen saver
613 refreshAll(); // will schedule periodic weather fetch
615 setWakeLock(mPluggedIn);
617 scheduleScreenSaver();
619 final boolean launchedFromDock
620 = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
622 if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) {
623 // policy: fetch weather if launched via dock connection
624 if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
625 requestWeatherDataFetch();
628 mLaunchedFromDock = launchedFromDock;
632 public void onPause() {
633 if (DEBUG) Log.d(LOG_TAG, "onPause");
635 // Turn off the screen saver and cancel any pending timeouts.
636 // (But don't un-dim.)
637 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
640 // Other things we don't want to be doing in the background.
641 unregisterReceiver(mIntentReceiver);
642 getContentResolver().unregisterContentObserver(mContentObserver);
644 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
645 am.cancel(mMidnightIntent);
646 unscheduleWeatherQuery();
651 private void initViews() {
652 // give up any internal focus before we switch layouts
653 final View focused = getCurrentFocus();
654 if (focused != null) focused.clearFocus();
656 setContentView(R.layout.desk_clock);
658 mTime = (DigitalClock) findViewById(R.id.time);
659 mDate = (TextView) findViewById(R.id.date);
660 mBatteryDisplay = (TextView) findViewById(R.id.battery);
662 mTime.getRootView().requestFocus();
664 mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
665 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
666 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
667 mWeatherLocation = (TextView) findViewById(R.id.weather_location);
668 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
670 final View.OnClickListener alarmClickListener = new View.OnClickListener() {
671 public void onClick(View v) {
672 startActivity(new Intent(DeskClock.this, AlarmClock.class));
676 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
677 mNextAlarm.setOnClickListener(alarmClickListener);
679 final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
680 alarmButton.setOnClickListener(alarmClickListener);
682 final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
683 galleryButton.setOnClickListener(new View.OnClickListener() {
684 public void onClick(View v) {
686 startActivity(new Intent(
688 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
689 .putExtra("slideshow", true)
690 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
691 } catch (android.content.ActivityNotFoundException e) {
692 Log.e(LOG_TAG, "Couldn't launch image browser", e);
697 final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
698 musicButton.setOnClickListener(new View.OnClickListener() {
699 public void onClick(View v) {
701 startActivity(new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER)
702 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
704 } catch (android.content.ActivityNotFoundException e) {
705 Log.e(LOG_TAG, "Couldn't launch music browser", e);
710 final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
711 homeButton.setOnClickListener(new View.OnClickListener() {
712 public void onClick(View v) {
714 new Intent(Intent.ACTION_MAIN)
715 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)
716 .addCategory(Intent.CATEGORY_HOME));
720 final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
721 nightmodeButton.setOnClickListener(new View.OnClickListener() {
722 public void onClick(View v) {
728 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
729 public boolean onLongClick(View v) {
735 final View weatherView = findViewById(R.id.weather);
736 weatherView.setOnClickListener(new View.OnClickListener() {
737 public void onClick(View v) {
738 if (!supportsWeather()) return;
740 Intent genieAppQuery = getPackageManager()
741 .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
742 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
743 if (genieAppQuery != null) {
744 startActivity(genieAppQuery);
749 final View tintView = findViewById(R.id.window_tint);
750 tintView.setOnTouchListener(new View.OnTouchListener() {
751 public boolean onTouch(View v, MotionEvent event) {
752 if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) {
753 // We want to un-dim the whole screen on tap.
754 // ...Unless the user is specifically tapping on the dim
755 // widget, in which case let it do the work.
757 nightmodeButton.getHitRect(r);
758 int[] gloc = new int[2];
759 nightmodeButton.getLocationInWindow(gloc);
760 r.offsetTo(gloc[0], gloc[1]); // convert to window coords
762 if (!r.contains((int) event.getX(), (int) event.getY())) {
767 return false; // always pass the click through
771 // Tidy up awkward focus behavior: the first view to be focused in
772 // trackball mode should be the alarms button
773 final ViewTreeObserver vto = alarmButton.getViewTreeObserver();
774 vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
775 public void onGlobalFocusChanged(View oldFocus, View newFocus) {
776 if (oldFocus == null && newFocus == nightmodeButton) {
777 alarmButton.requestFocus();
784 public void onConfigurationChanged(Configuration newConfig) {
785 super.onConfigurationChanged(newConfig);
786 if (mScreenSaverMode) {
796 public boolean onOptionsItemSelected(MenuItem item) {
797 switch (item.getItemId()) {
798 case R.id.menu_item_alarms:
799 startActivity(new Intent(DeskClock.this, AlarmClock.class));
801 case R.id.menu_item_add_alarm:
802 startActivity(new Intent(this, SetAlarm.class));
804 case R.id.menu_item_dock_settings:
805 startActivity(new Intent(DOCK_SETTINGS_ACTION));
813 public boolean onCreateOptionsMenu(Menu menu) {
814 MenuInflater inflater = getMenuInflater();
815 inflater.inflate(R.menu.desk_clock_menu, menu);
820 protected void onCreate(Bundle icicle) {
821 super.onCreate(icicle);
826 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
827 } catch (PackageManager.NameNotFoundException e) {
828 // no weather info available
829 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");