Guest User

Untitled

a guest
Sep 5th, 2013
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 41.75 KB | None | 0 0
  1. /*  File Version: 3.0
  2.  *  Copyright, David Book, buzztouch.com
  3.  *
  4.  *  All rights reserved.
  5.  *
  6.  *  Redistribution and use in source and binary forms, with or without modification, are
  7.  *  permitted provided that the following conditions are met:
  8.  *
  9.  *  Redistributions of source code must retain the above copyright notice which includes the
  10.  *  name(s) of the copyright holders. It must also retain this list of conditions and the
  11.  *  following disclaimer.
  12.  *
  13.  *  Redistributions in binary form must reproduce the above copyright notice, this list
  14.  *  of conditions and the following disclaimer in the documentation and/or other materials
  15.  *  provided with the distribution.
  16.  *
  17.  *  Neither the name of David Book, or buzztouch.com nor the names of its contributors
  18.  *  may be used to endorse or promote products derived from this software without specific
  19.  *  prior written permission.
  20.  *
  21.  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  22.  *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  23.  *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  24.  *  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  25.  *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  26.  *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27.  *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  28.  *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29.  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  30.  *  OF SUCH DAMAGE.
  31.  */
  32. package com.test;
  33. import static com.test.BT_gcmConfig.EXTRA_MESSAGE;
  34.  
  35. import org.json.JSONObject;
  36.  
  37. import android.app.Activity;
  38. import android.app.AlertDialog;
  39. import android.app.ProgressDialog;
  40. import android.content.BroadcastReceiver;
  41. import android.content.Context;
  42. import android.content.DialogInterface;
  43. import android.content.Intent;
  44. import android.content.IntentFilter;
  45. import android.content.res.Configuration;
  46. import android.graphics.drawable.Drawable;
  47. import android.location.Location;
  48. import android.location.LocationListener;
  49. import android.location.LocationManager;
  50. import android.os.AsyncTask;
  51. import android.os.Bundle;
  52. import android.os.Handler;
  53. import android.os.Looper;
  54. import android.os.Message;
  55. import android.view.Window;
  56. import android.view.WindowManager;
  57. import android.view.animation.AlphaAnimation;
  58. import android.view.animation.Animation;
  59. import android.widget.ImageView;
  60. import android.widget.ImageView.ScaleType;
  61. import android.widget.LinearLayout;
  62. import android.widget.RelativeLayout;
  63. import android.widget.Toast;
  64.  
  65. import com.google.android.gcm.GCMRegistrar;
  66. import com.startapp.android.publish.StartAppAd;
  67.  
  68.  
  69.  
  70. public class BT_activity_base extends Activity implements LocationListener{
  71.  
  72.     protected String activityName = "BT_activity_base";
  73.     public static Activity thisActivity = null;
  74.     public BackgroundImageWorkerThread backgroundImageWorkerThread = null;
  75.     public Handler backgroundImageWorkerHandler = null;
  76.     public boolean downloadInProgress = false;
  77.     public Drawable backgroundImage = null;
  78.     public AlertDialog myAlert = null;
  79.     public ProgressDialog progressBox = null;
  80.     public BT_progressSpinner progressSpinner = null;
  81.     protected BT_item screenData = null;
  82.     public BT_item tapScreenLoadObject = null;
  83.     public BT_item tapMenuItemObject = null;
  84.     public String appLastModifiedOnServer = "";
  85.     public RelativeLayout backgroundSolidColorView = null;
  86.     public RelativeLayout backgroundGradientColorView = null;
  87.     public ImageView backgroundImageView = null;
  88.     public LinearLayout baseContentView = null;
  89.     public LinearLayout titleContainerView = null;
  90.     private StartAppAd startAppAd = null;
  91.  
  92.     public LocationManager locationManager;
  93.     public int locationUpdateCount = 0;
  94.     public String locationListenerType = "";
  95.    
  96.     //task to register with GCM...
  97.     AsyncTask<Void, Void, Void> gcmRegisterTask;
  98.     public String gcmRegId = "";
  99.     boolean promptForPush = false;
  100.    
  101.     //visible / showing
  102.     public static final int INVISIBLE = 4;
  103.     public static final int VISIBLE = 0;
  104.    
  105.  
  106.     //////////////////////////////////////////////////////////////////////////
  107.     //activity life-cycle events.
  108.    
  109.     //onCreate
  110.     @Override
  111.     public void onCreate(Bundle savedInstanceState){
  112.         super.onCreate(savedInstanceState);
  113.  
  114.         BT_debugger.showIt(activityName + ":onCreate (BASE CLASS)");   
  115.  
  116.         //remember this activity...
  117.         thisActivity = this;
  118.        
  119.         //create handler to configure backgrounds...
  120.         backgroundImageWorkerHandler = new Handler();
  121.        
  122.         ///////////////////////////////////////////////////////////////////////
  123.         //register for push logic (gcm registration id may have expired)...
  124.        
  125.         if(test_appDelegate.rootApp.getPromptForPushNotifications().equals("1")  && test_appDelegate.rootApp.getRegisterForPushURL().length() > 3){
  126.             promptForPush = true;
  127.         }
  128.  
  129.         //if setup for push...
  130.         if(promptForPush){
  131.             try{
  132.                    
  133.                 GCMRegistrar.checkDevice(this);
  134.                 GCMRegistrar.checkManifest(this);
  135.                    
  136.                 //setup intent to "listen" for messages from GCM...
  137.                 registerReceiver(baseHandlePushReceiver, new IntentFilter("com.test.DISPLAY_MESSAGE"));        
  138.                    
  139.                 //get a possible existing gcmRegId...
  140.                 gcmRegId = GCMRegistrar.getRegistrationId(this);
  141.  
  142.             }catch(java.lang.NoClassDefFoundError e){
  143.                 BT_debugger.showIt(activityName + ":Error configuring Push Notification setup. EXCEPTION " + e.toString());
  144.             }
  145.         }
  146.        
  147.        
  148.         //see if this device is already registered...
  149.         if(gcmRegId.length() < 1 && promptForPush){
  150.            
  151.             //prompt user for "allow" push notifications if they have NOT previously said "no thanks"...
  152.             if(BT_fileManager.doesCachedFileExist("rejectedpush.txt")){
  153.                 BT_debugger.showIt(activityName + ":Device owner has rejected Push Notifications");
  154.             }else{
  155.                 confirmRegisterForPush();
  156.             }
  157.            
  158.         }
  159.        
  160.         //log message if device is already registered...
  161.         if(gcmRegId.length() > 1){
  162.             BT_debugger.showIt(activityName + ":Device is registered for Google Cloud Messaging (Push) with token: " + gcmRegId);
  163.         }
  164.        
  165.         //register for push logic...
  166.         ///////////////////////////////////////////////////////////////////////
  167.  
  168.        
  169.         /*
  170.          * set the screenData for this screen BEFORE setting the content view...
  171.          * If this Activity was started with passed-in payload then we started it from
  172.          * BT_activity_root when a tab was created. In this we use that tabs
  173.          * home-screen data and not the rootApp.currentScreenData. This is because the
  174.          * rootApp.currentScreenData property has not been set yet.
  175.          */
  176.         Intent startedFromIntent = getIntent();
  177.         int tabIndex = startedFromIntent.getIntExtra("tabIndex", -1);
  178.         if(tabIndex > -1){
  179.            
  180.             //get this tabs home-screen data
  181.             if(tabIndex == 0) this.screenData = test_appDelegate.rootApp.getTab0ScreenData();
  182.             if(tabIndex == 1) this.screenData = test_appDelegate.rootApp.getTab1ScreenData();
  183.             if(tabIndex == 2) this.screenData = test_appDelegate.rootApp.getTab2ScreenData();
  184.             if(tabIndex == 3) this.screenData = test_appDelegate.rootApp.getTab3ScreenData();
  185.             if(tabIndex == 4) this.screenData = test_appDelegate.rootApp.getTab4ScreenData();
  186.        
  187.         }else{
  188.            
  189.             //set the screen data..
  190.             this.screenData = test_appDelegate.rootApp.getCurrentScreenData();
  191.            
  192.             //#######################################################################################################
  193.             //if this intent was started with a JSON payload holding the screen data, use it...this means it was
  194.             //passed along in the BT_act_controller.java > loadScreenObject method (see line 335 of that file)
  195.             Bundle extras = getIntent().getExtras();
  196.             if(getIntent().getStringExtra("screenData") != null){
  197.                 String tmpJSON = extras.getString("screenData");
  198.                 try{
  199.                     JSONObject payloadScreenData = new JSONObject(tmpJSON);
  200.                     BT_item payloadScreen = new BT_item();
  201.                     if(payloadScreenData.has("itemId")) payloadScreen.setItemId(payloadScreenData.getString("itemId"));
  202.                     if(payloadScreenData.has("itemType")) payloadScreen.setItemType(payloadScreenData.getString("itemType"));
  203.                     if(payloadScreenData.has("itemNickname")) payloadScreen.setItemNickname(payloadScreenData.getString("itemNickname"));
  204.                     payloadScreen.setJsonObject(payloadScreenData);
  205.                    
  206.                     //is this a home screen?
  207.                     if(getIntent().getStringExtra("screenDataIsHomeScreen") != null){
  208.                         String tmpHomeScreen = extras.getString("screenDataIsHomeScreen");
  209.                         if(tmpHomeScreen.equalsIgnoreCase("1")){
  210.                             payloadScreen.setIsHomeScreen(true);
  211.                         }else{
  212.                             payloadScreen.setIsHomeScreen(false);
  213.                         }
  214.                     }  
  215.                    
  216.                     this.screenData = payloadScreen;
  217.                 }catch(Exception e){
  218.                     BT_debugger.showIt("BT_activity_base:onCreate EXCEPTION parsing payloadScreenData's JSON: " + tmpJSON);
  219.                 }
  220.             }
  221.             //#########################################################################################################
  222.            
  223.             //because we are not in the root of a tab we can adjust the status bar dynamically...
  224.             requestWindowFeature(Window.FEATURE_NO_TITLE);
  225.            
  226.             String statusBarStyle = BT_strings.getStyleValueForScreen(this.screenData, "statusBarStyle", "");
  227.             if(statusBarStyle.equalsIgnoreCase("hidden")){
  228.                 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
  229.             }else{
  230.                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
  231.              
  232.             }
  233.        
  234.         }
  235.                
  236.         //content view for "base" activity is empty (it must be set before sub-classes can set another content view)
  237.         setContentView(R.layout.act_base);
  238.        
  239.         //create a pretend lastModifiedDate file if one does not exist yet...
  240.         if(!BT_fileManager.doesCachedFileExist(test_appDelegate.cachedConfigModifiedFileName)){
  241.             BT_fileManager.saveTextFileToCache("{this is a pretend date}", test_appDelegate.cachedConfigModifiedFileName);
  242.         }
  243.        
  244.        
  245.        
  246.        
  247.     }
  248.    
  249.     //onStart
  250.     @Override
  251.     protected void onStart() {
  252.         BT_debugger.showIt(activityName + ":onStart (BASE CLASS)");
  253.  
  254.         super.onStart();
  255.         //BT_debugger.showIt(activityName + ":onStart");   
  256.        
  257.         //start location manager?
  258.        
  259.         /*  Location Manager Logic (turn on GPS?)
  260.             -------------------------------------
  261.             Should this device report it's location? The device will turn on it's GPS and begin
  262.             tracking it's location if three things are true:
  263.             1) The application's configuration data is set to "startLocationUpdates"
  264.             2) The user has not turned on "allow location tracking" in a BT_screen_settingsLocation
  265.             3) The device is capable of tracking it's location (has GPS)
  266.          */
  267.         //Save battery! We remember the last reported location in the app's delegate so we don't have to turn on the GSP for every screen...
  268.         if(!test_appDelegate.foundUpdatedLocation && test_appDelegate.rootApp.getRootDevice().canUseGPS()){
  269.             if(test_appDelegate.rootApp.getStartLocationUpdates().equalsIgnoreCase("1")){
  270.                 BT_debugger.showIt(activityName + ": start GPS is set to YES in the applications configuration data, trying to start GPS");
  271.                 if(!BT_strings.getPrefString("userAllowLocation").equalsIgnoreCase("prevent")){
  272.                     BT_debugger.showIt(activityName + ": user has not prevented the GPS from starting using a BT_screen_settingsLocation screen");
  273.                    
  274.                     //trigger method...
  275.                     getLastLocation();
  276.                    
  277.                 }else{
  278.                     BT_debugger.showIt(activityName + ": user has prevented the GPS from starting using a BT_screen_settingsLocation screen");
  279.                 }
  280.             }else{
  281.                 BT_debugger.showIt(activityName + ": start GPS is set to NO in the applications configuration data, not starting GPS");
  282.             }
  283.         }//already found location and saved it in the app's delegate.
  284.  
  285.        
  286.        
  287.     }
  288.    
  289.     //onResume
  290.     @Override
  291.    
  292.     public void onResume() {
  293.         BT_debugger.showIt(activityName + ":onResume (BASE CLASS)");   
  294.  
  295.        super.onResume();
  296.        //BT_debugger.showIt(activityName + ":onResume");
  297.        
  298.         //if this is a home-screen, reportToCloud...
  299.         if(this.screenData.isHomeScreen()){
  300.    
  301.             //must have dataURL's
  302.             if(test_appDelegate.rootApp.getDataURL().length() > 1 && test_appDelegate.rootApp.getReportToCloudURL().length() > 1){
  303.                
  304.                 this.reportToCloud();
  305.                
  306.             }else{
  307.                 BT_debugger.showIt(activityName + ":reportToCloud no dataURL and / or reportToCloudURL, both required for remote updates, not reporting.");
  308.             }
  309.            
  310.         }
  311.        
  312.         if (startAppAd == null) {
  313.               startAppAd = new StartAppAd(this);
  314.               startAppAd.load();
  315.         }
  316.        
  317.        
  318.    }
  319.    
  320.     //onPause
  321.     @Override
  322.     public void onPause() {
  323.         BT_debugger.showIt(activityName + ":onPause (BASE CLASS)");
  324.  
  325.         super.onPause();
  326.         if ( startAppAd != null) {
  327.             boolean showAd = startAppAd.doHome();
  328.         if (showAd) {
  329.           startAppAd = null;
  330.              }
  331.         }
  332.         //BT_debugger.showIt(activityName + ":onPause");   
  333.     }
  334.    
  335.     //onStop
  336.     @Override
  337.     protected void onStop(){
  338.         BT_debugger.showIt(activityName + ":onStop (BASE CLASS)"); 
  339.  
  340.         super.onStop();
  341.         //BT_debugger.showIt(activityName + ":onStop");
  342.     }  
  343.    
  344.     //onDestroy
  345.     @Override
  346.     public void onDestroy() {
  347.         BT_debugger.showIt(activityName + ":onDestroy (BASE CLASS)");  
  348.  
  349.         //kill possible GCM registration task...
  350.         if (gcmRegisterTask != null) {
  351.             gcmRegisterTask.cancel(true);
  352.         }
  353.         try{
  354.             unregisterReceiver(baseHandlePushReceiver);
  355.             GCMRegistrar.onDestroy(this);
  356.         }catch(Exception e){
  357.             //ignore...
  358.         }      
  359.         super.onDestroy();
  360.     }
  361.      
  362.     //handles keyboard hiding and rotation events
  363.     @Override
  364.     public void onConfigurationChanged(Configuration newConfig){
  365.         super.onConfigurationChanged(newConfig);
  366.           switch(newConfig.orientation){
  367.                 case  Configuration.ORIENTATION_LANDSCAPE:
  368.                     BT_debugger.showIt(activityName + ":onConfigurationChanged to landscape");
  369.                     test_appDelegate.rootApp.getRootDevice().updateDeviceOrientation("landscape");
  370.                 break;
  371.                 case Configuration.ORIENTATION_PORTRAIT:
  372.                     BT_debugger.showIt(activityName + ":onConfigurationChanged to portrait");
  373.                     test_appDelegate.rootApp.getRootDevice().updateDeviceOrientation("portrait");
  374.                     break;
  375.                 case Configuration.ORIENTATION_SQUARE:
  376.                     BT_debugger.showIt(activityName + ":onConfigurationChanged is square");
  377.                     test_appDelegate.rootApp.getRootDevice().updateDeviceOrientation("portrait");
  378.                     break;
  379.                 case Configuration.ORIENTATION_UNDEFINED:
  380.                     BT_debugger.showIt(activityName + ":onConfigurationChanged is unidentified");
  381.                     test_appDelegate.rootApp.getRootDevice().updateDeviceOrientation("portrait");
  382.                     break;
  383.                 default:
  384.           }  
  385.       //update device size so we can keep track...
  386.       test_appDelegate.rootApp.getRootDevice().updateDeviceSize();
  387.     }
  388.     //end activity life-cycle events
  389.     //////////////////////////////////////////////////////////////////////////
  390.        
  391.     //show alert message
  392.     public void showAlert(String theTitle, String theMessage) {
  393.         if(theTitle.equals("")) theTitle = "No Alert Title?";
  394.         if(theMessage.equals("")) theMessage = "No alert message?";
  395.         myAlert = new AlertDialog.Builder(this).create();
  396.         myAlert.setTitle(theTitle);
  397.         myAlert.setMessage(theMessage);
  398.         myAlert.setIcon(R.drawable.icon);
  399.         myAlert.setCancelable(false);
  400.         myAlert.setButton("OK", new DialogInterface.OnClickListener() {
  401.           public void onClick(DialogInterface dialog, int which) {
  402.             myAlert.dismiss();
  403.         } });
  404.         myAlert.show();
  405.     }  
  406.    
  407.     public static void showAlertFromClass(String theTitle, String theMessage){
  408.         if(theTitle.equals("")) theTitle = "No Alert Title?";
  409.         if(theMessage.equals("")) theMessage = "No alert message?";
  410.         final AlertDialog theAlert = new AlertDialog.Builder(thisActivity).create();
  411.         theAlert.setTitle(theTitle);
  412.         theAlert.setMessage(theMessage);
  413.         theAlert.setIcon(R.drawable.icon);
  414.         theAlert.setCancelable(false);
  415.         theAlert.setButton("OK", new DialogInterface.OnClickListener() {
  416.           public void onClick(DialogInterface dialog, int which) {
  417.               theAlert.dismiss();
  418.         } });
  419.         theAlert.show();   
  420.     }
  421.    
  422.     //show toast
  423.     public void showToast(String theMessage, String shortOrLong){
  424.         Toast toast = null;
  425.         if(shortOrLong.equalsIgnoreCase("short")){
  426.             toast = Toast.makeText(getBaseContext(), theMessage, Toast.LENGTH_SHORT);
  427.         }else{
  428.             toast = Toast.makeText(test_appDelegate.getContext(), theMessage, Toast.LENGTH_LONG);
  429.         }
  430.         toast.show();
  431.     }
  432.    
  433.    
  434.     //show / hide progress (two different types, depending on the message)...
  435.     public void showProgress(String theTitle, String theMessage){
  436.         if(theTitle == null && theMessage == null){
  437.             progressSpinner = BT_progressSpinner.show(this, null, null, true);
  438.         }else{
  439.             progressBox = ProgressDialog.show(this, theTitle, theMessage, true);
  440.         }
  441.     }
  442.     public void hideProgress(){
  443.         if(progressBox != null){
  444.             progressBox.dismiss();
  445.         }
  446.         if(progressSpinner != null){
  447.             progressSpinner.dismiss();
  448.         }
  449.     }
  450.    
  451.     //handles back button...
  452.     @Override
  453.     public void onBackPressed(){
  454.         BT_debugger.showIt(activityName + ":onBackPressed");
  455.         BT_debugger.showIt(activityName + ":REVERSING TRANSITIONS ARE DISABLED");
  456.         if (startAppAd != null) {
  457.               startAppAd.show();
  458.               startAppAd = null;    
  459.              }
  460.         super.onBackPressed();
  461.        
  462.         //figure out how to reverse a possible custom transition loaded in BT_act_controller.java
  463.         //overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
  464.        
  465.        
  466.  
  467.     }
  468.    
  469.     //confirm refresh...(asked after reportingToCloud)
  470.     public void confirmRefresh(){
  471.  
  472.         final AlertDialog confirmRefreshAlert = new AlertDialog.Builder(this).create();
  473.         confirmRefreshAlert.setTitle(getString(R.string.confirmRefreshTitle));
  474.         confirmRefreshAlert.setMessage(getString(R.string.confirmRefreshDescription));
  475.         confirmRefreshAlert.setIcon(R.drawable.icon);
  476.         confirmRefreshAlert.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() {
  477.           public void onClick(DialogInterface dialog, int which) {
  478.              
  479.               //refresh data...
  480.               confirmRefreshAlert.dismiss();
  481.               refreshAppData();
  482.              
  483.         } });
  484.         confirmRefreshAlert.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() {
  485.               public void onClick(DialogInterface dialog, int which) {
  486.                   confirmRefreshAlert.dismiss();
  487.             } });
  488.         confirmRefreshAlert.show();
  489.     }      
  490.    
  491.     //refreshes app data...
  492.     public void refreshAppData(){
  493.         BT_debugger.showIt(activityName + ":refreshAppData");
  494.        
  495.         //showToast...
  496.         showToast(getString(R.string.loadingTitle), "long");
  497.        
  498.         //finish this activity...
  499.         this.finish();
  500.        
  501.         //start BT_activity_root with "1" as payload to signal we are refreshing...
  502.        Intent i = new Intent(this, BT_activity_root.class);
  503.        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  504.        i.putExtra("isRefreshing", 1);
  505.        startActivity(i);
  506.        overridePendingTransition(R.anim.fadein, R.anim.fadeout);
  507.  
  508.        
  509.     }
  510.    
  511.     //confirm register for Push Notifications...
  512.     public void confirmRegisterForPush(){
  513.  
  514.         final AlertDialog confirmPushAlert = new AlertDialog.Builder(this).create();
  515.         confirmPushAlert.setTitle("Accept Push Notifications?");
  516.         confirmPushAlert.setMessage("This app would like to send you notifications and simple messages. Is this OK?");
  517.         confirmPushAlert.setIcon(R.drawable.icon);
  518.         confirmPushAlert.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() {
  519.           public void onClick(DialogInterface dialog, int which) {
  520.              
  521.               //dismiss dialgue...
  522.               confirmPushAlert.dismiss();
  523.              
  524.               //register for push...
  525.               registerForPush();
  526.              
  527.         } });
  528.         confirmPushAlert.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() {
  529.               public void onClick(DialogInterface dialog, int which) {
  530.                  
  531.                   //save a text file to remember that user "rejected push"...
  532.                   BT_fileManager.saveTextFileToCache("rejected", "rejectedpush.txt");
  533.  
  534.                   //dismiss dialgue..                
  535.                   confirmPushAlert.dismiss();
  536.                  
  537.             } });
  538.         confirmPushAlert.show();
  539.     }
  540.    
  541.     //register for Push Notifications...
  542.     public void registerForPush(){
  543.         BT_debugger.showIt(activityName + ":registerForPush");
  544.        
  545.         //remove "rejected push" file...
  546.         BT_fileManager.deleteFile("rejectedpush.txt");
  547.        
  548.         boolean doSetupForPush = false;
  549.         if(test_appDelegate.rootApp.getPromptForPushNotifications().equals("1")  && test_appDelegate.rootApp.getRegisterForPushURL().length() > 3){
  550.             doSetupForPush = true;
  551.         }
  552.        
  553.         //see if this device is already registered...
  554.         if(gcmRegId.equals("") && doSetupForPush){
  555.             BT_debugger.showIt(activityName + ":device is NOT registered with GCM (Google Cloud Messaging)");
  556.  
  557.             //GCMRegistration id not available, register now...
  558.             test_appDelegate.rootApp.setPushRegistrationId("");
  559.             GCMRegistrar.register(this, BT_gcmConfig.SENDER_ID);
  560.            
  561.         }
  562.        
  563.         //if we already have a registration id, make sure it's registered on server...
  564.         if(!gcmRegId.equals("") && doSetupForPush) {
  565.            
  566.             //device is registered on GCM already...
  567.             if(GCMRegistrar.isRegisteredOnServer(this)) {
  568.            
  569.                 BT_debugger.showIt(activityName + ":device is registered with GCM (Google Cloud Messaging)");
  570.                 test_appDelegate.rootApp.setPushRegistrationId(gcmRegId);
  571.  
  572.             }else{
  573.                
  574.                 //try to register again, off the UI thread...
  575.                 final Context context = this;
  576.                 gcmRegisterTask = new AsyncTask<Void, Void, Void>(){
  577.  
  578.                     @Override
  579.                     protected Void doInBackground(Void... params) {
  580.  
  581.                         //register on backend server...
  582.                         BT_gcmServerUtils.gcmRegisterOnServer(context, gcmRegId);
  583.                         return null;
  584.                     }
  585.  
  586.                     @Override
  587.                     protected void onPostExecute(Void result) {
  588.                         gcmRegisterTask = null;
  589.                     }
  590.  
  591.                 };
  592.                 gcmRegisterTask.execute(null, null, null);
  593.             }          
  594.         } //gcmRegId == ""
  595.        
  596.     }
  597.    
  598.     //unregister for push...
  599.     public void unregisterForPush(){
  600.         BT_debugger.showIt(activityName + ":unregisterForPush");
  601.        
  602.         //save a text file to remember that user "rejected push"...
  603.         BT_fileManager.saveTextFileToCache("rejected", "rejectedpush.txt");
  604.        
  605.         //try to register again, off the UI thread...
  606.         final Context context = this;
  607.         gcmRegisterTask = new AsyncTask<Void, Void, Void>(){
  608.  
  609.             @Override
  610.             protected Void doInBackground(Void... params) {
  611.  
  612.                 //register on backend server...
  613.                 BT_gcmServerUtils.gcmUnregisterOnServer(context, gcmRegId);
  614.                 return null;
  615.             }
  616.  
  617.             @Override
  618.             protected void onPostExecute(Void result) {
  619.                 gcmRegisterTask = null;
  620.             }
  621.  
  622.         };
  623.         gcmRegisterTask.execute(null, null, null);
  624.        
  625.     }  
  626.    
  627.  
  628.     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  629.     //BackgroundWorkerThread and Handler. Loads a possible image (from bundle, cache, or a URL) then calls handler..
  630.  
  631.     //handles image download when complete...
  632.     private Runnable setBackgroundImage = new Runnable(){
  633.         public void run(){
  634.             BT_debugger.showIt(activityName + ":setBackgroundImage: returned to UI Thread...");
  635.  
  636.             //find background image view...
  637.             backgroundImageView = (ImageView) thisActivity.findViewById(R.id.backgroundImageView);
  638.            
  639.             //global theme used if this screen doesn't override a setting...
  640.             BT_item theThemeData = test_appDelegate.rootApp.getRootTheme();
  641.            
  642.             //does the file exist in the project bundle...
  643.             if(backgroundImage != null && backgroundImageView != null){
  644.                 BT_debugger.showIt(activityName + ":setBackgroundImage: setting background image");
  645.  
  646.                 //make sure imageView is visible..
  647.                 backgroundImageView.setVisibility(1);
  648.                
  649.                 //background scale...
  650.                 String backgroundImageScale = "";
  651.                 if(BT_strings.getJsonPropertyValue(screenData.getJsonObject(), "backgroundImageScale", "").length() > 1){
  652.                     backgroundImageScale = BT_strings.getJsonPropertyValue(screenData.getJsonObject(), "backgroundImageScale", "");
  653.                 }else{
  654.                     backgroundImageScale = BT_strings.getJsonPropertyValue(theThemeData.getJsonObject(), "backgroundImageScale", "");
  655.                 }
  656.                    
  657.                 if(backgroundImageScale.equalsIgnoreCase("center")) backgroundImageView.setScaleType(ScaleType.CENTER);
  658.                 if(backgroundImageScale.equalsIgnoreCase("fullScreen")) backgroundImageView.setScaleType(ScaleType.FIT_XY);
  659.                 if(backgroundImageScale.equalsIgnoreCase("fullScreenPreserve")) backgroundImageView.setScaleType(ScaleType.FIT_CENTER);
  660.                 if(backgroundImageScale.equalsIgnoreCase("top")) backgroundImageView.setScaleType(ScaleType.FIT_START);
  661.                 if(backgroundImageScale.equalsIgnoreCase("bottom")) backgroundImageView.setScaleType(ScaleType.FIT_END);
  662.                 if(backgroundImageScale.equalsIgnoreCase("topLeft")) backgroundImageView.setScaleType(ScaleType.FIT_START);
  663.                 if(backgroundImageScale.equalsIgnoreCase("topRight")) backgroundImageView.setScaleType(ScaleType.FIT_START);
  664.                 if(backgroundImageScale.equalsIgnoreCase("bottomLeft")) backgroundImageView.setScaleType(ScaleType.FIT_END);
  665.                 if(backgroundImageScale.equalsIgnoreCase("bottomRight")) backgroundImageView.setScaleType(ScaleType.FIT_END);
  666.                
  667.                 //set the image...
  668.                 backgroundImageView.setImageDrawable(backgroundImage);
  669.                 backgroundImageView.invalidate();
  670.                
  671.                 //fade in background image...
  672.                 Animation animation = new AlphaAnimation(0.0f, 1.0f);
  673.                 animation.setDuration(500);
  674.                 backgroundImageView.startAnimation(animation);
  675.                
  676.                
  677.             }else{
  678.                 //BT_debugger.showIt(activityName + ":setBackgroundImage: This screen does not use a background image");
  679.             }
  680.            
  681.             //hideProgress;
  682.             hideProgress();
  683.            
  684.         }//run
  685.     }; 
  686.    
  687.     public class BackgroundImageWorkerThread extends Thread{
  688.          public void run(){
  689.             try{
  690.                
  691.                 //backround image name or url, small or large device...
  692.                 String backgroundImageName = "";
  693.                 String backgroundImageURL = "";
  694.                 if(test_appDelegate.rootApp.getRootDevice().getIsLargeDevice()){
  695.                    
  696.                     //large device background...
  697.                     backgroundImageName = BT_strings.getStyleValueForScreen(screenData, "backgroundImageNameLargeDevice", "");
  698.                     backgroundImageURL = BT_strings.getStyleValueForScreen(screenData, "backgroundImageURLLargeDevice", "");
  699.                            
  700.                 }else{
  701.                
  702.                     //large device background...
  703.                     backgroundImageName = BT_strings.getStyleValueForScreen(screenData, "backgroundImageNameSmallDevice", "");
  704.                     backgroundImageURL = BT_strings.getStyleValueForScreen(screenData, "backgroundImageURLSmallDevice", "");
  705.                    
  706.                 }//small or large device...
  707.                
  708.                 //use a local or cached image if we have one, else, download...
  709.                 String useImageName = "";
  710.                 if(backgroundImageName.length() > 1){
  711.                     useImageName = backgroundImageName;
  712.                 }else{
  713.                     if(backgroundImageURL.length() > 1){
  714.                         useImageName = BT_strings.getSaveAsFileNameFromURL(backgroundImageURL);
  715.                     }
  716.                 }
  717.                
  718.                 //does the file exist in the project bundle...
  719.                 if(useImageName.length() > 1){
  720.                    
  721.                     //does image exist in /res/drawable folder...
  722.                     if(BT_fileManager.getResourceIdFromBundle("drawable", useImageName) > 0){
  723.                        
  724.                         BT_debugger.showIt(activityName + ":backgroundWorkerThread using image from project bundle: \"" + useImageName + "\"");
  725.                         backgroundImage = BT_fileManager.getDrawableByName(useImageName);
  726.                        
  727.                     }else{
  728.                        
  729.                         //does file exist in cache...
  730.                         if(BT_fileManager.doesCachedFileExist(useImageName)){
  731.                            
  732.                             BT_debugger.showIt(activityName + ":backgroundWorkerThread using image from cache: \"" + useImageName + "\"");
  733.                             backgroundImage = BT_fileManager.getDrawableFromCache(useImageName);
  734.                        
  735.                         }else{
  736.                            
  737.                             //download from URL if we have one...
  738.                             if(backgroundImageURL.length() > 1){
  739.                                
  740.                                 //if we have a url..
  741.                                 if(useImageName.length() > 1){
  742.                                     //don't bother pulling name from URL, already have it..
  743.                                 }else{
  744.                                     if(backgroundImageURL.length() > 1){
  745.                                         useImageName = BT_strings.getSaveAsFileNameFromURL(backgroundImageURL);
  746.                                     }
  747.                                 }
  748.                                
  749.                                 BT_downloader objDownloader = new BT_downloader(backgroundImageURL);
  750.                                 objDownloader.setSaveAsFileName(useImageName);
  751.                                 backgroundImage = objDownloader.downloadDrawable();
  752.                                
  753.                                 //print to log of failed...
  754.                                 if(backgroundImage == null){
  755.                                     BT_debugger.showIt(activityName + ":backgroundWorkerThread NOT SAVING iamge to cache (null)");
  756.                                 }
  757.                             }
  758.                            
  759.                         }//cached file exists
  760.                     }//bundle file exists
  761.                 }else{//usesImageName
  762.                     BT_debugger.showIt(activityName + ":backgroundWorkerThread this screen does not use a background image");
  763.                 }
  764.                
  765.                 //fire handler in main UI thread if we have an image...
  766.                 if(backgroundImage != null){
  767.                     backgroundImageWorkerHandler.post(setBackgroundImage);
  768.                 }
  769.                
  770.             }catch(Exception e){
  771.                 BT_debugger.showIt(activityName + ":backgroundWorkerThread Exception: " + e.toString());
  772.             }
  773.            
  774.          }//run      
  775.     };
  776.     //end BackgroundWorkerThread and Handler   
  777.     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  778.    
  779.     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  780.     //handles messages after report to cloud thread completes...
  781.     private Handler mHandler = new Handler(){
  782.         @Override
  783.         public void handleMessage(Message msg){
  784.            
  785.             //hide progress...
  786.             hideProgress();
  787.            
  788.             //compare, save, continue..
  789.             String cachedConfigModifiedFileName = test_appDelegate.cachedConfigModifiedFileName;
  790.             String previousModified = "";
  791.            
  792.             //parse returned data...
  793.             try{
  794.            
  795.                 JSONObject obj = new JSONObject(appLastModifiedOnServer);
  796.                 if(obj.has("lastModifiedUTC")){
  797.                     appLastModifiedOnServer = obj.getString("lastModifiedUTC");
  798.                     BT_debugger.showIt(activityName + ":handleReportToCloudResults appLastModifiedOnServer (value on server): " + appLastModifiedOnServer);
  799.                 }
  800.                
  801.                 //ignore if we don't have a "server date"
  802.                 if(appLastModifiedOnServer.length() > 1){
  803.  
  804.                     //see if we have a cached lastModified file...
  805.                     if(BT_fileManager.doesCachedFileExist(cachedConfigModifiedFileName)){
  806.                         previousModified = BT_fileManager.readTextFileFromCache(cachedConfigModifiedFileName);
  807.                         BT_debugger.showIt(activityName + ":handleReportToCloudResults previousModified (value on device): " + previousModified);
  808.                     }
  809.                
  810.                     //save downloaded lastModifiedDate
  811.                     BT_fileManager.saveTextFileToCache(appLastModifiedOnServer, cachedConfigModifiedFileName);
  812.                
  813.                     //do we prompt for refresh?
  814.                     if(appLastModifiedOnServer.length() > 3 && previousModified.length() > 3){
  815.                         if(!appLastModifiedOnServer.equalsIgnoreCase(previousModified)){
  816.                             BT_debugger.showIt(activityName + ":handleReportToCloudResults server data changed, app needs refreshed");
  817.                             confirmRefresh();
  818.                         }else{
  819.                             BT_debugger.showIt(activityName + ":handleReportToCloudResults server data not changed, no refresh needed");
  820.                         }
  821.        
  822.                     }
  823.                        
  824.                 }//appLastModifiedOnServer
  825.                
  826.             }catch(Exception e){
  827.                 BT_debugger.showIt(activityName + ":handleReportToCloudResults EXCEPTION processing results: " + e.toString());
  828.             }          
  829.            
  830.         }
  831.     };
  832.    
  833.     //reportToCloud
  834.     public void reportToCloud(){
  835.         BT_debugger.showIt(activityName + ":reportToCloud");           
  836.  
  837.         new Thread(){
  838.            
  839.             @Override
  840.             public void run(){
  841.                
  842.                 //prepare looper...
  843.                 Looper.prepare();
  844.  
  845.                 //dataURL and reportToCloudURL may be empty or not used at all...
  846.                 String dataURL = BT_strings.mergeBTVariablesInString(test_appDelegate.rootApp.getDataURL());
  847.                 String reportToCloudURL = BT_strings.mergeBTVariablesInString(test_appDelegate.rootApp.getReportToCloudURL());
  848.                
  849.                 //do we have a data URL for remote updates?
  850.                 if(dataURL.length() < 1){
  851.                     BT_debugger.showIt(activityName + ":reportToCloudWorkerThread does not use a dataURL, automatic updates disabled.");           
  852.                 }
  853.                 if(reportToCloudURL.length() < 1){
  854.                     BT_debugger.showIt(activityName + ":reportToCloudWorkerThread does not use a reportToCloudURL, automatic updates disabled.");          
  855.                 }                      
  856.                
  857.                 //if we have a dataURL AND a reportToCloudURL...report to cloud...
  858.                 if(dataURL.length() > 5 && reportToCloudURL.length() > 5){
  859.                    
  860.                     //if we have a currentMode, append it to the end of the URL...
  861.                     if(test_appDelegate.rootApp.getCurrentMode().length() > 1){
  862.                         reportToCloudURL += "&currentMode=" + test_appDelegate.rootApp.getCurrentMode();
  863.                     }                  
  864.                    
  865.                     BT_debugger.showIt(activityName + ":reportToCloudWorkerThread getting lastModified from reportToCloudURL " + reportToCloudURL);
  866.                
  867.                     BT_downloader objDownloader = new BT_downloader(reportToCloudURL);
  868.                     objDownloader.setSaveAsFileName("");
  869.                     appLastModifiedOnServer = objDownloader.downloadTextData();
  870.  
  871.                 }//dataURL.length()
  872.                    
  873.                 //send message...
  874.                 sendMessageToMainThread(0);
  875.                
  876.             }
  877.            
  878.             //send message....
  879.             private void sendMessageToMainThread(int what){
  880.                 Message msg = Message.obtain();
  881.                 msg.what = what;
  882.                 mHandler.sendMessage(msg);
  883.             }
  884.            
  885.         }.start();
  886.        
  887.     }
  888.     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  889.    
  890.  
  891.      
  892.      
  893.     ////////////////////////////////////////////////////////////////////
  894.      //Location Manager Methods
  895.      public void getLastLocation(){
  896.          try{
  897.             //only ask for location info "once" when app launches (saves battery)
  898.             if(!test_appDelegate.foundUpdatedLocation){
  899.                 locationUpdateCount = 0;
  900.                 if(this.locationManager == null){
  901.                     this.locationUpdateCount = 0;
  902.                     this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);  
  903.                 }
  904.                 if(this.locationManager != null){
  905.                     Location lastLocation = this.locationManager.getLastKnownLocation("gps");
  906.                     if(lastLocation != null){
  907.                        
  908.                        
  909.                         //remember in delegate
  910.                         test_appDelegate.rootApp.getRootDevice().setDeviceLatitude(String.valueOf(lastLocation.getLatitude()));
  911.                         test_appDelegate.rootApp.getRootDevice().setDeviceLongitude(String.valueOf(lastLocation.getLongitude()));
  912.  
  913.                         String s = "";
  914.                         //s += " Updated: " + lastLocation.getTime();
  915.                         s += " Lat: " + lastLocation.getLatitude();
  916.                         s += " Lon: " + lastLocation.getLongitude();
  917.                         s += " Accuracy: " + lastLocation.getAccuracy();
  918.                         BT_debugger.showIt(activityName + ":getLastLocation " + s);
  919.                        
  920.                     }
  921.                     //start listening for location updates if we have GPS enabled...
  922.                     if(this.locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
  923.                         locationListenerType = "GPS";
  924.                         startListening();
  925.                     }else{
  926.                         if(this.locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
  927.                             locationListenerType = "NETWORK/CELL";
  928.                             startListening();
  929.                         }else{
  930.                             BT_debugger.showIt(activityName + ":getLastLocation Can't start GPS or Network Services to get location info.");
  931.                         }
  932.                     }
  933.                    
  934.                 }else{
  935.                     BT_debugger.showIt(activityName + ":getLastLocation locationManager == null?");
  936.                 }
  937.             }
  938.          }catch (Exception je){
  939.             BT_debugger.showIt(activityName + ":getLastLocation EXCEPTION " + je.toString());
  940.         }
  941.      }
  942.    
  943.     //LocationListener must implement these methods
  944.     public void onProviderDisabled(String theProvider){
  945.         BT_debugger.showIt(activityName + ":onProviderDisabled The GPS is disabled on this device.");
  946.     };    
  947.     public void onProviderEnabled(String theProvider){
  948.         BT_debugger.showIt(activityName + ":onProviderDisabled The GPS is enabled on this device.");
  949.     };
  950.     public void onLocationChanged(Location location){
  951.         this.locationUpdateCount++;
  952.         BT_debugger.showIt(activityName + ":onLocationChanged The device's location changed.");
  953.        
  954.         try{
  955.  
  956.             /*
  957.                 Example of how to get the device's current location in any code you write anywhere in your app....
  958.  
  959.                 String myLatitude = test_appDelegate.rootApp.getRootDevice().getDeviceLatitude();
  960.                 String myLongitude = test_appDelegate.rootApp.getRootDevice().getDeviceLongitude();
  961.                
  962.                 Then convert myLatitude and myLongitude strings to doubles, integers, floats as needed.
  963.              
  964.             */
  965.            
  966.             test_appDelegate.rootApp.getRootDevice().setDeviceLatitude(String.valueOf(location.getLatitude()));
  967.             test_appDelegate.rootApp.getRootDevice().setDeviceLongitude(String.valueOf(location.getLongitude()));
  968.            
  969.             String s = "";
  970.             s += "From: " + locationListenerType;
  971.             //s += " Updated: " + location.getTime();
  972.             s += " Lat:: " + location.getLatitude();
  973.             s += " Lon:: " + location.getLongitude();
  974.             s += " Accuracy:: " + location.getAccuracy();
  975.             BT_debugger.showIt(activityName + ":onLocationChanged " + s);
  976.            
  977.             //stop listening after 10 reports (about 10 seconds) or if we have good accuracy faster....
  978.             if(locationUpdateCount > 10 || location.getAccuracy() < 25){
  979.                 BT_debugger.showIt(activityName + ":onLocationChanged turning off GPS to save battery, saved last location.");
  980.                
  981.                 //flag foundUpdatedLocation in the delgate so other screens don't turn on the GPS              
  982.                 test_appDelegate.foundUpdatedLocation = true;
  983.                
  984.                 //stop listening (kill the locationManager)...
  985.                 stopListening();
  986.                
  987.             }
  988.         }catch(Exception e){
  989.            
  990.         }
  991.     };
  992.     public void onStatusChanged(String theProvider, int status, Bundle extras){
  993.         try{
  994.             BT_debugger.showIt(activityName + ":onStatusChanged (for the location manager)");
  995.         }catch(Exception e){
  996.            
  997.         }
  998.     };
  999.     //start listening..
  1000.     public void startListening(){
  1001.         BT_debugger.showIt(activityName + ":startListening (started listening for location changes)");
  1002.         try{
  1003.             if(this.locationManager != null){
  1004.                
  1005.                 //we we started this in getLastLocation() we set a flag to tell us what type of service to setup..
  1006.                 if(locationListenerType == "GPS"){
  1007.                     //request updates from GPS...
  1008.                     this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
  1009.                     BT_debugger.showIt(activityName + ":startListening asking for GPS locations updates...");
  1010.                 }
  1011.                 if(locationListenerType == "NETWORK/CELL"){
  1012.                     //request updates from Network (Cell Towwers, Wi-Fi)...
  1013.                     this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
  1014.                     BT_debugger.showIt(activityName + ":startListening asking for Network (Cell Tower or Wi-Fi) location updates...");
  1015.                 }
  1016.                
  1017.             }
  1018.         }catch(Exception e){
  1019.         }
  1020.      }
  1021.     //stop listening..
  1022.     public void stopListening(){
  1023.         BT_debugger.showIt(activityName + ":startListening (stopped listening to location changes)");
  1024.         try{
  1025.             if(this.locationManager != null){
  1026.                 this.locationManager.removeUpdates(this);
  1027.                 this.locationManager = null;
  1028.             }
  1029.         }catch(Exception e){
  1030.            
  1031.         }
  1032.      }
  1033.     //END location methods
  1034.     ////////////////////////////////////////////////////////////////////
  1035.  
  1036.    
  1037.     ////////////////////////////////////////////////////////////////////
  1038.     //Broadcast Receiver to handle Push Notifications...
  1039.     private final BroadcastReceiver baseHandlePushReceiver = new BroadcastReceiver() {
  1040.         @Override
  1041.         public void onReceive(Context context, Intent intent) {
  1042.             BT_debugger.showIt(activityName + ":BroadcastReceiver baseHandlePushReceiver");
  1043.             String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
  1044.            
  1045.             //wake device if sleeping...
  1046.             BT_gcmWakeLocker.acquire(getApplicationContext());
  1047.      
  1048.             //show quick toast so user knows a new message arrived...
  1049.             showToast(newMessage, "short");
  1050.                
  1051.             //releasing wake lock
  1052.             BT_gcmWakeLocker.release();
  1053.                
  1054.         }//getIntent
  1055.     };  
  1056.     ////////////////////////////////////////////////////////////////////
  1057.    
  1058.    
  1059.    
  1060.     //get / set screenData...  
  1061.     public BT_item getScreenData() {
  1062.         return this.screenData;
  1063.     }
  1064.  
  1065.     public void setScreenData(BT_item theScreenData) {
  1066.         this.screenData = theScreenData;
  1067.     }    
  1068.      
  1069.  
  1070. }
Advertisement
Add Comment
Please, Sign In to add comment