OSDN Git Service

Merge change I2763ab4c into eclair
[android-x86/packages-apps-DeskClock.git] / src / com / android / deskclock / DeskClock.java
1 /*
2  * Copyright (C) 2009 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.android.deskclock;
18
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.ColorDrawable;
32 import android.graphics.drawable.Drawable;
33 import android.net.Uri;
34 import android.os.Bundle;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.os.SystemClock;
38 import android.provider.Settings;
39 import android.text.TextUtils;
40 import android.util.Log;
41 import android.view.ContextMenu.ContextMenuInfo;
42 import android.view.ContextMenu;
43 import android.view.LayoutInflater;
44 import android.view.Menu;
45 import android.view.MenuItem;
46 import android.view.View.OnClickListener;
47 import android.view.View.OnCreateContextMenuListener;
48 import android.view.View;
49 import android.view.ViewGroup;
50 import android.view.Window;
51 import android.view.WindowManager;
52 import android.view.animation.AnimationUtils;
53 import android.widget.AdapterView.AdapterContextMenuInfo;
54 import android.widget.AdapterView.OnItemClickListener;
55 import android.widget.AdapterView;
56 import android.widget.Button;
57 import android.widget.CheckBox;
58 import android.widget.ImageView;
59 import android.widget.TextView;
60
61 import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
62 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
63 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
64
65 import java.io.IOException;
66 import java.io.InputStream;
67 import java.text.DateFormat;
68 import java.util.Date;
69
70 /**
71  * DeskClock clock view for desk docks.
72  */
73 public class DeskClock extends Activity {
74     private static final boolean DEBUG = true;
75
76     private static final String LOG_TAG = "DeskClock";
77
78     private static final String MUSIC_NOW_PLAYING_ACTIVITY = "com.android.music.PLAYBACK_VIEWER";
79
80     private final long FETCH_WEATHER_DELAY = 5 * 60 * 1000; // 5 min.
81     private final int FETCH_WEATHER_DATA_MSG = 10000;
82     private final int UPDATE_WEATHER_DISPLAY_MSG = 10001;
83
84     private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
85     private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
86     private static final String WEATHER_CONTENT_PATH = "/weather/current";
87     private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
88             "location",
89             "timestamp",
90             "highTemperature",
91             "lowTemperature",
92             "iconUrl",
93             "iconResId",
94             "description",
95         };
96
97     private DigitalClock mTime;
98     private TextView mDate;
99
100     private TextView mNextAlarm = null;
101     private TextView mBatteryDisplay;
102
103     private TextView mWeatherTemperature;
104     private TextView mWeatherLocation;
105     private ImageView mWeatherIcon;
106
107     private String mWeatherTemperatureString;
108     private String mWeatherLocationString;
109     private Drawable mWeatherIconDrawable;
110
111     private Resources mGenieResources = null;
112
113     private boolean mDimmed = false;
114
115     private DateFormat mDateFormat;
116     
117     private int mBatteryLevel;
118     private boolean mPluggedIn;
119
120     private boolean mWeatherFetchScheduled = false;
121
122     private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
123         @Override
124         public void onReceive(Context context, Intent intent) {
125             final String action = intent.getAction();
126             if (Intent.ACTION_DATE_CHANGED.equals(action)) {
127                 refreshDate();
128             } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
129                 handleBatteryUpdate(
130                     intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
131                     intent.getIntExtra("level", 0));
132             }
133         }
134     };
135
136     private final Handler mHandy = new Handler() {
137         @Override
138         public void handleMessage(Message m) {
139             if (DEBUG) Log.d(LOG_TAG, "handleMessage: " + m.toString());
140
141             if (m.what == FETCH_WEATHER_DATA_MSG) {
142                 if (!mWeatherFetchScheduled) return;
143                 mWeatherFetchScheduled = false;
144                 new Thread() { public void run() { fetchWeatherData(); } }.start();
145                 scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY);
146             } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
147                 updateWeatherDisplay();
148             }
149         }
150     };
151
152     private boolean supportsWeather() {
153         return (mGenieResources != null);
154     }
155
156     private void scheduleWeatherFetchDelayed(long delay) {
157         if (mWeatherFetchScheduled) return;
158
159         if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
160
161         mWeatherFetchScheduled = true;
162
163         mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay);
164     }
165
166     private void unscheduleWeatherFetch() {
167         mWeatherFetchScheduled = false;
168     }
169
170     private void fetchWeatherData() {
171         // if we couldn't load the weather widget's resources, we simply
172         // assume it's not present on the device.
173         if (mGenieResources == null) return;
174
175         Uri queryUri = new Uri.Builder()
176             .scheme(android.content.ContentResolver.SCHEME_CONTENT)
177             .authority(WEATHER_CONTENT_AUTHORITY)
178             .path(WEATHER_CONTENT_PATH)
179             .appendPath(new Long(System.currentTimeMillis()).toString())
180             .build();
181
182         if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
183
184         Cursor cur;
185         try {
186             cur = managedQuery(
187                 queryUri,
188                 WEATHER_CONTENT_COLUMNS,
189                 null,
190                 null,
191                 null);
192         } catch (RuntimeException e) {
193             Log.e(LOG_TAG, "Weather query failed", e);
194             cur = null;
195         }
196
197         if (cur != null && cur.moveToFirst()) {
198             mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
199                 cur.getColumnIndexOrThrow("iconResId")));
200             mWeatherTemperatureString = cur.getString(
201                 cur.getColumnIndexOrThrow("highTemperature"));
202             mWeatherLocationString = cur.getString(
203                 cur.getColumnIndexOrThrow("location"));
204         } else {
205             Log.w(LOG_TAG, "No weather information available (cur=" 
206                 + cur +")");
207             mWeatherIconDrawable = null;
208             mWeatherTemperatureString = "";
209             mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize
210         }
211
212         mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
213     }
214
215     private void refreshWeather() {
216         if (supportsWeather())
217             scheduleWeatherFetchDelayed(0);
218     }
219
220     private void updateWeatherDisplay() {
221         mWeatherTemperature.setText(mWeatherTemperatureString);
222         mWeatherLocation.setText(mWeatherLocationString);
223         mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
224     }
225
226     // Adapted from KeyguardUpdateMonitor.java
227     private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
228         final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
229         if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
230             mBatteryLevel = batteryLevel;
231             mPluggedIn = pluggedIn;
232             refreshBattery();
233         }
234     }
235
236     private void refreshBattery() {
237         if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
238             mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
239                 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
240             mBatteryDisplay.setText(
241                 getString(R.string.battery_charging_level, mBatteryLevel));
242             mBatteryDisplay.setVisibility(View.VISIBLE);
243         } else {
244             mBatteryDisplay.setVisibility(View.INVISIBLE);
245         }
246     }
247
248     private void refreshDate() {
249         mDate.setText(mDateFormat.format(new Date()));
250     }
251
252     private void refreshAlarm() {
253         String nextAlarm = Settings.System.getString(getContentResolver(),
254                 Settings.System.NEXT_ALARM_FORMATTED);
255         if (!TextUtils.isEmpty(nextAlarm)) {
256             mNextAlarm.setText(nextAlarm);
257             //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
258             //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
259             mNextAlarm.setVisibility(View.VISIBLE);
260         } else {
261             mNextAlarm.setVisibility(View.INVISIBLE);
262         }
263     }
264
265     private void refreshAll() {
266         refreshDate();
267         refreshAlarm();
268         refreshBattery();
269         refreshWeather();
270     }
271
272     private void doDim(boolean fade) {
273         View tintView = findViewById(R.id.window_tint);
274
275         Window win = getWindow();
276         WindowManager.LayoutParams winParams = win.getAttributes();
277
278         // dim the wallpaper somewhat (how much is determined below)
279         winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
280
281         if (mDimmed) {
282             winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
283 //            winParams.flags &= (~WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
284             winParams.dimAmount = 0.5f; // pump up contrast in dim mode
285
286             // show the window tint
287             tintView.startAnimation(AnimationUtils.loadAnimation(this, 
288                 fade ? R.anim.dim
289                      : R.anim.dim_instant));
290         } else {
291             winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
292 //            winParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
293             winParams.dimAmount = 0.2f; // lower contrast in normal mode
294     
295             // hide the window tint
296             tintView.startAnimation(AnimationUtils.loadAnimation(this, 
297                 fade ? R.anim.undim
298                      : R.anim.undim_instant));
299         }
300         
301         win.setAttributes(winParams);
302     }
303
304     @Override
305     public void onResume() {
306         super.onResume();
307
308         // reload the date format in case the user has changed settings
309         // recently
310         mDateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
311
312         IntentFilter filter = new IntentFilter();
313         filter.addAction(Intent.ACTION_DATE_CHANGED);
314         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
315         registerReceiver(mIntentReceiver, filter);
316
317         doDim(false);
318         refreshAll();
319     }
320
321     @Override
322     public void onPause() {
323         super.onPause();
324         unregisterReceiver(mIntentReceiver);
325         unscheduleWeatherFetch();
326     }
327
328
329     private void initViews() {
330         setContentView(R.layout.desk_clock);
331
332         mTime = (DigitalClock) findViewById(R.id.time);
333         mDate = (TextView) findViewById(R.id.date);
334         mBatteryDisplay = (TextView) findViewById(R.id.battery);
335
336         mWeatherTemperature = (TextView) findViewById(R.id.weather_temperature);
337         mWeatherLocation = (TextView) findViewById(R.id.weather_location);
338         mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
339
340         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
341
342         final Button alarmButton = (Button) findViewById(R.id.alarm_button);
343         alarmButton.setOnClickListener(new View.OnClickListener() {
344             public void onClick(View v) {
345                 startActivity(new Intent(DeskClock.this, AlarmClock.class));
346             }
347         });
348
349         final Button galleryButton = (Button) findViewById(R.id.gallery_button);
350         galleryButton.setOnClickListener(new View.OnClickListener() {
351             public void onClick(View v) {
352                 try {
353                     startActivity(new Intent(
354                         Intent.ACTION_VIEW,
355                         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
356                 } catch (android.content.ActivityNotFoundException e) {
357                     Log.e(LOG_TAG, "Couldn't launch image browser", e);
358                 }
359             }
360         });
361
362         final Button musicButton = (Button) findViewById(R.id.music_button);
363         musicButton.setOnClickListener(new View.OnClickListener() {
364             public void onClick(View v) {
365                 try {
366                     startActivity(new Intent(MUSIC_NOW_PLAYING_ACTIVITY));
367                 } catch (android.content.ActivityNotFoundException e) {
368                     Log.e(LOG_TAG, "Couldn't launch music browser", e);
369                 }
370             }
371         });
372
373         final Button homeButton = (Button) findViewById(R.id.home_button);
374         homeButton.setOnClickListener(new View.OnClickListener() {
375             public void onClick(View v) {
376                 startActivity(
377                     new Intent(Intent.ACTION_MAIN)
378                         .addCategory(Intent.CATEGORY_HOME));
379             }
380         });
381
382         final Button nightmodeButton = (Button) findViewById(R.id.nightmode_button);
383         nightmodeButton.setOnClickListener(new View.OnClickListener() {
384             public void onClick(View v) {
385                 mDimmed = ! mDimmed;
386                 doDim(true);
387             }
388         });
389     }
390
391     @Override
392     public void onConfigurationChanged(Configuration newConfig) {
393         super.onConfigurationChanged(newConfig);
394         initViews();
395         doDim(false);
396         refreshAll();
397     }
398
399     @Override
400     protected void onCreate(Bundle icicle) {
401         super.onCreate(icicle);
402
403         try {
404             mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
405         } catch (PackageManager.NameNotFoundException e) {
406             // no weather info available
407             Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
408         }
409
410         initViews();
411     }
412
413 }