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 // Delay before engaging the burn-in protection mode (green-on-black).
106 private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min
108 // Repositioning delay in screen saver.
109 private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
111 // Color to use for text & graphics in screen saver mode.
112 private final int SCREEN_SAVER_COLOR = 0xFF308030;
113 private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018;
115 // Opacity of black layer between clock display and wallpaper.
116 private final float DIM_BEHIND_AMOUNT_NORMAL = 0.4f;
117 private final float DIM_BEHIND_AMOUNT_DIMMED = 0.8f; // higher contrast when display dimmed
119 // Internal message IDs.
120 private final int QUERY_WEATHER_DATA_MSG = 0x1000;
121 private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
122 private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000;
123 private final int SCREEN_SAVER_MOVE_MSG = 0x2001;
125 // Weather widget query information.
126 private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
127 private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
128 private static final String WEATHER_CONTENT_PATH = "/weather/current";
129 private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
140 private static final String ACTION_GENIE_REFRESH = "com.google.android.apps.genie.REFRESH";
142 // State variables follow.
143 private DigitalClock mTime;
144 private TextView mDate;
146 private TextView mNextAlarm = null;
147 private TextView mBatteryDisplay;
149 private TextView mWeatherCurrentTemperature;
150 private TextView mWeatherHighTemperature;
151 private TextView mWeatherLowTemperature;
152 private TextView mWeatherLocation;
153 private ImageView mWeatherIcon;
155 private String mWeatherCurrentTemperatureString;
156 private String mWeatherHighTemperatureString;
157 private String mWeatherLowTemperatureString;
158 private String mWeatherLocationString;
159 private Drawable mWeatherIconDrawable;
161 private Resources mGenieResources = null;
163 private boolean mDimmed = false;
164 private boolean mScreenSaverMode = false;
166 private String mDateFormat;
168 private int mBatteryLevel = -1;
169 private boolean mPluggedIn = false;
171 private boolean mLaunchedFromDock = false;
175 private PendingIntent mMidnightIntent;
177 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
179 public void onReceive(Context context, Intent intent) {
180 final String action = intent.getAction();
181 if (DEBUG) Log.d(LOG_TAG, "mIntentReceiver.onReceive: action=" + action + ", intent=" + intent);
182 if (Intent.ACTION_DATE_CHANGED.equals(action) || ACTION_MIDNIGHT.equals(action)) {
184 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
186 intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
187 intent.getIntExtra("level", 0));
188 } else if (Intent.ACTION_DOCK_EVENT.equals(action)) {
189 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, -1);
190 if (DEBUG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT, state=" + state);
191 if (state == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
192 if (mLaunchedFromDock) {
193 // moveTaskToBack(false);
196 mLaunchedFromDock = false;
202 private final Handler mHandy = new Handler() {
204 public void handleMessage(Message m) {
205 if (m.what == QUERY_WEATHER_DATA_MSG) {
206 new Thread() { public void run() { queryWeatherData(); } }.start();
207 scheduleWeatherQueryDelayed(QUERY_WEATHER_DELAY);
208 } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
209 updateWeatherDisplay();
210 } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
212 } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
218 private final ContentObserver mContentObserver = new ContentObserver(mHandy) {
220 public void onChange(boolean selfChange) {
221 if (DEBUG) Log.d(LOG_TAG, "content observer notified that weather changed");
227 private void moveScreenSaver() {
228 moveScreenSaverTo(-1,-1);
230 private void moveScreenSaverTo(int x, int y) {
231 if (!mScreenSaverMode) return;
233 final View saver_view = findViewById(R.id.saver_view);
235 DisplayMetrics metrics = new DisplayMetrics();
236 getWindowManager().getDefaultDisplay().getMetrics(metrics);
238 if (x < 0 || y < 0) {
239 int myWidth = saver_view.getMeasuredWidth();
240 int myHeight = saver_view.getMeasuredHeight();
241 x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
242 y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
245 if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
246 System.currentTimeMillis(), x, y));
248 saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams(
249 ViewGroup.LayoutParams.WRAP_CONTENT,
250 ViewGroup.LayoutParams.WRAP_CONTENT,
254 // Synchronize our jumping so that it happens exactly on the second.
255 mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
256 SCREEN_SAVER_MOVE_DELAY +
257 (1000 - (System.currentTimeMillis() % 1000)));
260 private void setWakeLock(boolean hold) {
261 if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
262 Window win = getWindow();
263 WindowManager.LayoutParams winParams = win.getAttributes();
264 winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
265 winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
266 winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
268 winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
270 winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
271 win.setAttributes(winParams);
274 private void scheduleScreenSaver() {
275 // reschedule screen saver
276 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
277 mHandy.sendMessageDelayed(
278 Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG),
279 SCREEN_SAVER_TIMEOUT);
282 private void restoreScreen() {
283 if (!mScreenSaverMode) return;
284 if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
285 mScreenSaverMode = false;
287 doDim(false); // restores previous dim mode
288 // policy: update weather info when returning from screen saver
289 if (mPluggedIn) requestWeatherDataFetch();
291 scheduleScreenSaver();
296 // Special screen-saver mode for OLED displays that burn in quickly
297 private void saveScreen() {
298 if (mScreenSaverMode) return;
299 if (DEBUG) Log.d(LOG_TAG, "saveScreen");
301 // quickly stash away the x/y of the current date
302 final View oldTimeDate = findViewById(R.id.time_date);
303 int oldLoc[] = new int[2];
304 oldTimeDate.getLocationOnScreen(oldLoc);
306 mScreenSaverMode = true;
307 Window win = getWindow();
308 WindowManager.LayoutParams winParams = win.getAttributes();
309 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
310 win.setAttributes(winParams);
312 // give up any internal focus before we switch layouts
313 final View focused = getCurrentFocus();
314 if (focused != null) focused.clearFocus();
316 setContentView(R.layout.desk_clock_saver);
318 mTime = (DigitalClock) findViewById(R.id.time);
319 mDate = (TextView) findViewById(R.id.date);
320 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
322 final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
324 ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
325 ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
326 mDate.setTextColor(color);
327 mNextAlarm.setTextColor(color);
328 mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
329 getResources().getDrawable(mDimmed
330 ? R.drawable.ic_lock_idle_alarm_saver_dim
331 : R.drawable.ic_lock_idle_alarm_saver),
335 mWeatherCurrentTemperature =
336 mWeatherHighTemperature =
337 mWeatherLowTemperature =
338 mWeatherLocation = null;
344 moveScreenSaverTo(oldLoc[0], oldLoc[1]);
348 public void onUserInteraction() {
349 if (mScreenSaverMode)
353 // Tell the Genie widget to load new data from the network.
354 private void requestWeatherDataFetch() {
355 if (DEBUG) Log.d(LOG_TAG, "forcing the Genie widget to update weather now...");
356 sendBroadcast(new Intent(ACTION_GENIE_REFRESH).putExtra("requestWeather", true));
357 // we expect the result to show up in our content observer
360 private boolean supportsWeather() {
361 return (mGenieResources != null);
364 private void scheduleWeatherQueryDelayed(long delay) {
365 // cancel any existing scheduled queries
366 unscheduleWeatherQuery();
368 if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
370 mHandy.sendEmptyMessageDelayed(QUERY_WEATHER_DATA_MSG, delay);
373 private void unscheduleWeatherQuery() {
374 mHandy.removeMessages(QUERY_WEATHER_DATA_MSG);
377 private void queryWeatherData() {
378 // if we couldn't load the weather widget's resources, we simply
379 // assume it's not present on the device.
380 if (mGenieResources == null) return;
382 Uri queryUri = new Uri.Builder()
383 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
384 .authority(WEATHER_CONTENT_AUTHORITY)
385 .path(WEATHER_CONTENT_PATH)
386 .appendPath(new Long(System.currentTimeMillis()).toString())
389 if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
395 WEATHER_CONTENT_COLUMNS,
399 } catch (RuntimeException e) {
400 Log.e(LOG_TAG, "Weather query failed", e);
404 if (cur != null && cur.moveToFirst()) {
406 java.lang.StringBuilder sb =
407 new java.lang.StringBuilder("Weather query result: {");
408 for(int i=0; i<cur.getColumnCount(); i++) {
409 if (i>0) sb.append(", ");
410 sb.append(cur.getColumnName(i))
412 .append(cur.getString(i));
415 Log.d(LOG_TAG, sb.toString());
418 mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
419 cur.getColumnIndexOrThrow("iconResId")));
420 mWeatherCurrentTemperatureString = String.format("%d\u00b0",
421 (cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
422 mWeatherHighTemperatureString = String.format("%d\u00b0",
423 (cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
424 mWeatherLowTemperatureString = String.format("%d\u00b0",
425 (cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
426 mWeatherLocationString = cur.getString(
427 cur.getColumnIndexOrThrow("location"));
429 Log.w(LOG_TAG, "No weather information available (cur="
431 mWeatherIconDrawable = null;
432 mWeatherHighTemperatureString = "";
433 mWeatherLowTemperatureString = "";
434 mWeatherLocationString = getString(R.string.weather_fetch_failure);
437 mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
440 private void refreshWeather() {
441 if (supportsWeather())
442 scheduleWeatherQueryDelayed(0);
443 updateWeatherDisplay(); // in case we have it cached
446 private void updateWeatherDisplay() {
447 if (mWeatherCurrentTemperature == null) return;
449 mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
450 mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
451 mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
452 mWeatherLocation.setText(mWeatherLocationString);
453 mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
456 // Adapted from KeyguardUpdateMonitor.java
457 private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
458 final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
459 if (pluggedIn != mPluggedIn) {
460 setWakeLock(pluggedIn);
463 // policy: update weather info when attaching to power
464 requestWeatherDataFetch();
467 if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
468 mBatteryLevel = batteryLevel;
469 mPluggedIn = pluggedIn;
474 private void refreshBattery() {
475 if (mBatteryDisplay == null) return;
477 if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
478 mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
479 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
480 mBatteryDisplay.setText(
481 getString(R.string.battery_charging_level, mBatteryLevel));
482 mBatteryDisplay.setVisibility(View.VISIBLE);
484 mBatteryDisplay.setVisibility(View.INVISIBLE);
488 private void refreshDate() {
489 final Date now = new Date();
490 if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
491 mDate.setText(DateFormat.format(mDateFormat, now));
494 private void refreshAlarm() {
495 if (mNextAlarm == null) return;
497 String nextAlarm = Settings.System.getString(getContentResolver(),
498 Settings.System.NEXT_ALARM_FORMATTED);
499 if (!TextUtils.isEmpty(nextAlarm)) {
500 mNextAlarm.setText(nextAlarm);
501 //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
502 // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
503 mNextAlarm.setVisibility(View.VISIBLE);
505 mNextAlarm.setVisibility(View.INVISIBLE);
509 private void refreshAll() {
516 private void doDim(boolean fade) {
517 View tintView = findViewById(R.id.window_tint);
518 if (tintView == null) return;
520 Window win = getWindow();
521 WindowManager.LayoutParams winParams = win.getAttributes();
523 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
524 winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
526 // dim the wallpaper somewhat (how much is determined below)
527 winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
530 winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
531 winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED;
533 // show the window tint
534 tintView.startAnimation(AnimationUtils.loadAnimation(this,
536 : R.anim.dim_instant));
538 winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
539 winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL;
541 // hide the window tint
542 tintView.startAnimation(AnimationUtils.loadAnimation(this,
544 : R.anim.undim_instant));
547 win.setAttributes(winParams);
551 public void onNewIntent(Intent newIntent) {
552 super.onNewIntent(newIntent);
553 if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
555 // update our intent so that we can consult it to determine whether or
556 // not the most recent launch was via a dock event
557 setIntent(newIntent);
561 public void onResume() {
563 if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent());
565 // reload the date format in case the user has changed settings
567 mDateFormat = getString(com.android.internal.R.string.full_wday_month_day_no_year);
569 IntentFilter filter = new IntentFilter();
570 filter.addAction(Intent.ACTION_DATE_CHANGED);
571 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
572 filter.addAction(Intent.ACTION_DOCK_EVENT);
573 filter.addAction(ACTION_MIDNIGHT);
574 registerReceiver(mIntentReceiver, filter);
576 // Listen for updates to weather data
577 Uri weatherNotificationUri = new Uri.Builder()
578 .scheme(android.content.ContentResolver.SCHEME_CONTENT)
579 .authority(WEATHER_CONTENT_AUTHORITY)
580 .path(WEATHER_CONTENT_PATH)
582 getContentResolver().registerContentObserver(
583 weatherNotificationUri, true, mContentObserver);
585 // Elaborate mechanism to find out when the day rolls over
586 Calendar today = Calendar.getInstance();
587 today.set(Calendar.HOUR_OF_DAY, 0);
588 today.set(Calendar.MINUTE, 0);
589 today.set(Calendar.SECOND, 0);
590 today.add(Calendar.DATE, 1);
591 long alarmTimeUTC = today.getTimeInMillis() + today.get(Calendar.ZONE_OFFSET);
592 mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
593 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
594 am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent);
595 if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at "
596 + alarmTimeUTC + " repeating every "
597 + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent);
599 // If we weren't previously visible but now we are, it's because we're
600 // being started from another activity. So it's OK to un-dim.
601 if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) {
605 // Adjust the display to reflect the currently chosen dim mode.
608 restoreScreen(); // disable screen saver
609 refreshAll(); // will schedule periodic weather fetch
611 setWakeLock(mPluggedIn);
613 scheduleScreenSaver();
615 final boolean launchedFromDock
616 = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
618 if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) {
619 // policy: fetch weather if launched via dock connection
620 if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
621 requestWeatherDataFetch();
624 mLaunchedFromDock = launchedFromDock;
628 public void onPause() {
629 if (DEBUG) Log.d(LOG_TAG, "onPause");
631 // Turn off the screen saver and cancel any pending timeouts.
632 // (But don't un-dim.)
633 mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
636 // Other things we don't want to be doing in the background.
637 unregisterReceiver(mIntentReceiver);
638 getContentResolver().unregisterContentObserver(mContentObserver);
640 AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
641 am.cancel(mMidnightIntent);
642 unscheduleWeatherQuery();
647 private void initViews() {
648 // give up any internal focus before we switch layouts
649 final View focused = getCurrentFocus();
650 if (focused != null) focused.clearFocus();
652 setContentView(R.layout.desk_clock);
654 mTime = (DigitalClock) findViewById(R.id.time);
655 mDate = (TextView) findViewById(R.id.date);
656 mBatteryDisplay = (TextView) findViewById(R.id.battery);
658 mTime.getRootView().requestFocus();
660 mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
661 mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
662 mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
663 mWeatherLocation = (TextView) findViewById(R.id.weather_location);
664 mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
666 final View.OnClickListener alarmClickListener = new View.OnClickListener() {
667 public void onClick(View v) {
668 startActivity(new Intent(DeskClock.this, AlarmClock.class));
672 mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
673 mNextAlarm.setOnClickListener(alarmClickListener);
675 final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
676 alarmButton.setOnClickListener(alarmClickListener);
678 final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
679 galleryButton.setOnClickListener(new View.OnClickListener() {
680 public void onClick(View v) {
682 startActivity(new Intent(
684 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
685 .putExtra("slideshow", true)
686 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
687 } catch (android.content.ActivityNotFoundException e) {
688 Log.e(LOG_TAG, "Couldn't launch image browser", e);
693 final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
694 musicButton.setOnClickListener(new View.OnClickListener() {
695 public void onClick(View v) {
697 Intent musicAppQuery = getPackageManager()
698 .getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
699 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
700 if (musicAppQuery != null) {
701 startActivity(musicAppQuery);
703 } catch (android.content.ActivityNotFoundException e) {
704 Log.e(LOG_TAG, "Couldn't launch music browser", e);
709 final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
710 homeButton.setOnClickListener(new View.OnClickListener() {
711 public void onClick(View v) {
713 new Intent(Intent.ACTION_MAIN)
714 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)
715 .addCategory(Intent.CATEGORY_HOME));
719 final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
720 nightmodeButton.setOnClickListener(new View.OnClickListener() {
721 public void onClick(View v) {
727 nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
728 public boolean onLongClick(View v) {
734 final View weatherView = findViewById(R.id.weather);
735 weatherView.setOnClickListener(new View.OnClickListener() {
736 public void onClick(View v) {
737 if (!supportsWeather()) return;
739 Intent genieAppQuery = getPackageManager()
740 .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
741 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
742 if (genieAppQuery != null) {
743 startActivity(genieAppQuery);
748 final View tintView = findViewById(R.id.window_tint);
749 tintView.setOnTouchListener(new View.OnTouchListener() {
750 public boolean onTouch(View v, MotionEvent event) {
751 if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) {
752 // We want to un-dim the whole screen on tap.
753 // ...Unless the user is specifically tapping on the dim
754 // widget, in which case let it do the work.
756 nightmodeButton.getHitRect(r);
757 int[] gloc = new int[2];
758 nightmodeButton.getLocationInWindow(gloc);
759 r.offsetTo(gloc[0], gloc[1]); // convert to window coords
761 if (!r.contains((int) event.getX(), (int) event.getY())) {
766 return false; // always pass the click through
770 // Tidy up awkward focus behavior: the first view to be focused in
771 // trackball mode should be the alarms button
772 final ViewTreeObserver vto = alarmButton.getViewTreeObserver();
773 vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
774 public void onGlobalFocusChanged(View oldFocus, View newFocus) {
775 if (oldFocus == null && newFocus == nightmodeButton) {
776 alarmButton.requestFocus();
783 public void onConfigurationChanged(Configuration newConfig) {
784 super.onConfigurationChanged(newConfig);
785 if (mScreenSaverMode) {
795 public boolean onOptionsItemSelected(MenuItem item) {
796 if (item.getItemId() == R.id.menu_item_alarms) {
797 startActivity(new Intent(DeskClock.this, AlarmClock.class));
799 } else if (item.getItemId() == R.id.menu_item_add_alarm) {
800 AlarmClock.addNewAlarm(this);
807 public boolean onCreateOptionsMenu(Menu menu) {
808 MenuInflater inflater = getMenuInflater();
809 inflater.inflate(R.menu.desk_clock_menu, menu);
814 protected void onCreate(Bundle icicle) {
815 super.onCreate(icicle);
820 mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
821 } catch (PackageManager.NameNotFoundException e) {
822 // no weather info available
823 Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");