Merge branch 'master' of ssh://cahost.average.org/~/WhereAmI
[WhereAmI.git] / src / org / average / whereami / WhereAmI.java
index 11867938dfed201f1baca8a0cd6d9f36b6d51766..2fed78cbbada79d093932cee1959f7943ea85fa0 100644 (file)
 package org.average.whereami;
 
+import org.average.whereami.WhereAmIprefs;
+import org.average.whereami.Oracle;
+import org.average.whereami.PhoneLog;
+import org.average.whereami.Location;
+
 import android.app.Activity;
+import android.net.wifi.WifiManager;
 import android.os.Bundle;
 import android.os.AsyncTask;
 import android.os.Handler;
-import android.os.SystemClock;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.content.BroadcastReceiver;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.Context;
+import android.content.res.Resources;
+import android.content.SharedPreferences;
+import android.preference.PreferenceManager;
+import android.text.format.Time;
 import android.util.Log;
 import android.view.View;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
 import android.view.Window;
 import android.view.WindowManager;
 import android.widget.TextView;
 
 public class WhereAmI extends Activity
 {
-    private TextView tv;
+    final String TAG = getClass().getName();
 
-    /** Called when the activity is first created. */
-    @Override
-    public void onCreate(Bundle savedInstanceState)
-    {
-        super.onCreate(savedInstanceState);
-        requestWindowFeature(Window.FEATURE_NO_TITLE);
-        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
-        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
-        setContentView(R.layout.main);
-        tv = (TextView)findViewById(R.id.tv);
-        Log.v("WhereAmI", "created UI, about to start update task");
-       mHandler.postDelayed(updateClock, 2000);
-        Log.v("WhereAmI", "created UI, update task created");
+    private WifiManager wifiman;
+    private Boolean managewifi = false;
+    private Long updatedelay = 60000L;
+    private Integer runningtasks = 0;
+    private SharedPreferences prefs;
+
+    private class UpdateTarget {
+        private TextView tv;
+        private Oracle updater;
+        private BgUpdate task;
+
+        private class BgUpdate extends AsyncTask<Void, Void, String> {
+            @Override
+            protected String doInBackground(Void... params) {
+                Log.w(TAG, "BgUpdate " + updater + " starting");
+                return updater.getResult();
+            }
+        
+            @Override
+            protected void onPostExecute(String str) {
+                Log.w(TAG, "BgUpdate callback executing");
+                tv.setText(str);
+                runningtasks--;
+                if (runningtasks <= 0) {
+                    boolean wifion = wifiman.setWifiEnabled(false);
+                    Log.w(TAG, "disabling wifi result " + wifion);
+                    Time tm = new Time();
+                    tm.setToNow();
+                    tvs.setText(R.string.lasttry);
+                    tvs.append(tm.format(" %d/%m/%Y %H:%M:%S"));
+                }
+            }
+
+            @Override
+            protected void onCancelled() {
+                Log.w(TAG, "BgUpdate callback cancelled");
+                runningtasks--;
+            }
+        }
+
+        public UpdateTarget(TextView tv, Oracle updater) {
+            this.tv = tv;
+            this.updater = updater;
+        }
+
+        public void launch() {
+            tv.setText(R.string.updating);
+            task = new BgUpdate();
+            task.execute();
+        }
+
+        public void cancel() {
+            task.cancel(true);
+        }
     }
+    private UpdateTarget[] ut;
+
+    private TextView tvt, tvd, tvs;
+    private Resources res;
+    private String[] month;
+    private String[] wday;
 
     private Handler mHandler = new Handler();
 
     private Runnable updateClock = new Runnable () {
         public void run() {
-            long millis = System.currentTimeMillis();
-            Log.v("updateClock", "executing");
-            // new TimedUpdateTask().execute(5); // for delayed execution
-            tv.setText(Long.toString(millis));
-            mHandler.postDelayed(this, 2000);
+            long now = System.currentTimeMillis();
+            Time tm = new Time();
+            tm.set(now);
+            tvt.setText(tm.format("%H:%M"));
+            tm.set(now + 60000);
+            tm.second=0;
+            long next = tm.toMillis(false);
+            mHandler.postDelayed(this, next-now+1);
+        }
+    };
+
+    private Runnable updateCal = new Runnable () {
+        public void run() {
+            long now = System.currentTimeMillis();
+            Time tm = new Time();
+            tm.set(now);
+            tvd.setText(
+                       wday[tm.weekDay] +
+                       tm.format("\n%d ") +
+                       month[tm.month] +
+                       tm.format(" %Y"));
+            tm.set(now + 86400000);
+            tm.hour=0;
+            tm.minute=0;
+            tm.second=0;
+            long next = tm.toMillis(false);
+            mHandler.postDelayed(this, next-now+1);
+        }
+    };
+
+    private Runnable updateInfo = new Runnable () {
+        public void run() {
+            Log.w(TAG, "updateInfo starting");
+            if (managewifi) {
+                IntentFilter intentFilter =
+                    new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
+                registerReceiver(connChanged,intentFilter);
+                connChangedRegistered = true;
+                boolean wifion = wifiman.setWifiEnabled(true);
+                Log.w(TAG, "enabling wifi result " + wifion);
+            } else {
+                for (int i = 0; i < ut.length; i++) {
+                    runningtasks++;
+                    ut[i].launch();
+                }
+            }
+            mHandler.postDelayed(resetInfo, 50000);
+            mHandler.postDelayed(this, updatedelay);
+        }
+    };
+
+    private Runnable resetInfo = new Runnable () {
+        public void run() {
+            Log.w(TAG, "resetInfo starting");
+            if (connChangedRegistered) {
+                unregisterReceiver(connChanged);
+                connChangedRegistered = false;
+            }
+            if (runningtasks > 0) {
+                for (int i = 0; i < ut.length; i++) {
+                    ut[i].cancel();
+                }
+                Time tm = new Time();
+                tm.setToNow();
+                tvs.setText(R.string.failtry);
+                tvs.append(tm.format(" %d/%m/%Y %H:%M:%S"));
+            }
+            if (managewifi) {
+                boolean wifion = wifiman.setWifiEnabled(false);
+                Log.w(TAG, "disabling wifi result " + wifion);
+            }
         }
     };
 
-    private class TimedUpdateTask extends AsyncTask<Integer, Void, String> {
-       @Override
-        protected String doInBackground(Integer... howlong) {
-            Log.v("TimedUpdateTask", "starting");
-            try {
-                Thread.sleep(1000 * howlong[0]);
-            } catch (InterruptedException e) {
-                Log.e("TimedUpdateTask", "sleep interrupted");
+    private boolean connChangedRegistered = false;
+    private final BroadcastReceiver connChanged = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            ConnectivityManager cm = (ConnectivityManager)context.
+                           getSystemService(Context.CONNECTIVITY_SERVICE);
+            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
+            boolean isConnected = activeNetwork != null &&
+                                  activeNetwork.isConnectedOrConnecting();
+            Log.w(TAG, "Connectivity changed to " + isConnected);
+            if (isConnected) {
+                for (int i = 0; i < ut.length; i++) {
+                    runningtasks++;
+                    ut[i].launch();
+                }
             }
-            Log.v("TimedUpdateTask", "about to return");
-            return (Integer.toString(howlong[0]) + " seconds passed");
         }
-    
-       @Override
-        protected void onPostExecute(String str) {
-            Log.v("TimedUpdateTask", "callback executing");
-            tv.setText(str);
+    };
+
+    /** Called when the activity is first created. */
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        wifiman = (WifiManager)getSystemService(Context.WIFI_SERVICE);
+        requestWindowFeature(Window.FEATURE_NO_TITLE);
+        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+        setContentView(R.layout.main);
+        res = getResources();
+        month = res.getStringArray(R.array.month);
+        wday = res.getStringArray(R.array.wday);
+        tvt = (TextView)findViewById(R.id.time);
+        tvd = (TextView)findViewById(R.id.date);
+        tvs = (TextView)findViewById(R.id.timestamp);
+       ut = new UpdateTarget[] {
+            new UpdateTarget((TextView)findViewById(R.id.location),
+                             new PhoneLog()),
+            new UpdateTarget((TextView)findViewById(R.id.phonecall),
+                             new Location())
+        };
+        Log.w(TAG, "created UI, about to start update task");
+       mHandler.post(updateClock);
+       mHandler.post(updateCal);
+       mHandler.post(updateInfo);
+        Log.w(TAG, "created UI, update task created");
+    }
+
+    /** Called when reactivated */
+    @Override
+    public void onResume() {
+        super.onResume();
+        prefs = PreferenceManager.getDefaultSharedPreferences(this);
+        boolean fullscreen = prefs.getBoolean("fullscreen", false);
+        managewifi = prefs.getBoolean("managewifi", false);
+        updatedelay = Long.parseLong(prefs.getString("updateperiod", "1200000"));
+        Log.w("WhereAmI", "fullscreen: " + fullscreen +
+                          ", managewifi: " + managewifi +
+                          ", updatedelay: " + updatedelay);
+        if (fullscreen) {
+            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
+            getWindow().clearFlags(WindowManager.LayoutParams.
+                                                  FLAG_FORCE_NOT_FULLSCREEN);
+        } else {
+            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
+        }
+    }
+
+    /** Called when put to background */
+    @Override
+    public void onPause() {
+        super.onPause();
+        Log.w(TAG, "going background");
+    }
+
+    /** Called when the activity is destroyed. */
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        Log.w(TAG, "going down");
+       mHandler.removeCallbacks(updateClock);
+       mHandler.removeCallbacks(updateCal);
+       mHandler.removeCallbacks(updateInfo);
+        if (connChangedRegistered) {
+            unregisterReceiver(connChanged);
+            connChangedRegistered = false;
+        }
+        boolean wifion = wifiman.setWifiEnabled(false);
+        Log.w(TAG, "disabling wifi result " + wifion);
+    }
+
+    /** Called when the menu is activated. */
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        MenuInflater inflater = getMenuInflater();
+        inflater.inflate(R.menu.main_menu, menu);
+        return true;
+    }
+
+    /** Called when the menu item is selected */
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        switch (item.getItemId()) {
+        case R.id.quit:
+            finish();
+            return true;
+        case R.id.authorize:
+            Log.w(TAG, "authorize requested");
+            startActivity(new Intent(this, Authorize.class));
+            return true;
+        case R.id.settings:
+            Log.w(TAG, "settings requested");
+            startActivity(new Intent(this, WhereAmIprefs.class));
+            return true;
+        default:
+            return super.onOptionsItemSelected(item);
         }
     }
 }