// Populate views from intent
  private void populateViews(Intent intent) {

    // Log startup intent
    ContentQuery.dumpIntent(intent);

    // Check to see if Cadpage is operating in restricted mode, and if it is
    // launch the donation status menu.  We'll check the donation status again
    // when this menu is closed
    if (!DonationManager.instance().isEnabled()) {
      MainDonateEvent.instance().doEvent(this, null);
    }

    // Retrieve message from queue
    SmsMessageQueue msgQueue = SmsMessageQueue.getInstance();
    int msgId = intent.getIntExtra(EXTRAS_MSG_ID, 0);
    SmsMmsMessage msg = msgQueue.getMessage(msgId);

    // This shouldn't be possible, unless someone other than SmsReceiver is
    // sending rouge intents to us.  But we had better catch it, just in case
    if (msg == null) {
      finish();
      return;
    }

    // Flag message read
    msg.setRead(true);
    msgQueue.notifyDataChange();

    // Populate views from message
    populateViews(msg);
  }
  /**
   * Make any necessary adjustments necessary when the location preference is changed
   *
   * @param location new location preference value
   * @param change true if location value has been changed
   */
  private void adjustLocationChange(String location, boolean change) {

    // If location changes, recalculate the donation status
    if (!location.equals(saveLocation)) {
      saveLocation = location;
      DonationManager.instance().reset();
      MainDonateEvent.instance().refreshStatus();
    }

    // Get the parser and see if it has a default filter
    // Save it in parserFilter so other preferences know what it is
    MsgParser parser = ManageParsers.getInstance().getParser(location);
    parserFilter = parser.getFilter();
    parserDefCity = parser.getDefaultCity();
    parserDefState = parser.getDefaultState();

    // If the parser has a filter, enable the override checkbox, set its value to true
    // And insert the default filter value in the summary off message
    // And unilaterally enable the general alert box
    if (parserFilter.length() > 0) {
      overrideFilterPref.setEnabled(true);
      if (change) overrideFilterPref.setChecked(false);
      overrideFilterPref.setSummaryOff(
          getString(R.string.pref_override_filter_summaryoff, parserFilter));
      filterPref.setEnabled(overrideFilterPref.isChecked());
      genAlertPref.setEnabled(true);
    }

    // If there is no parser filter, the override box is disabled but forced to true
    // the general alert box is enabled only if the user filter
    else {
      overrideFilterPref.setEnabled(false);
      overrideFilterPref.setChecked(true);
      filterPref.setEnabled(true);
      String filter = filterPref.getText();
      genAlertPref.setEnabled(filter.length() > 1);
    }

    // Any time the location parser changes, reset the override default loc setting
    // OK, its a little more complicated than that.  If the override default setting
    // is on, we can just turn it off and let the onPreferenceChange listener take
    // care of things.  If it is already off, we have to call the onPreferenceChange
    // listener ourselves so it will update the propert summary displays
    // If that isn't complicated enough, the overrideDefaultPref setting won't
    // be initialized the first time we are called, but that first call has the
    // change parameter set to false, so this logic gets skipped.
    if (change) {
      if (overrideDefaultPref.isChecked()) {
        overrideDefaultPref.setChecked(false);
      } else {
        overrideDefaultPref
            .getOnPreferenceChangeListener()
            .onPreferenceChange(overrideDefaultPref, false);
      }
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Save location so we can tell when it changes
    saveLocation = ManagePreferences.location();

    // Build preference tree
    addPreferencesFromResource(R.xml.preferences);

    // Set preferences initialized flag
    ManagePreferences.setInitialized(true);

    // Set up the two enable components preferences
    Preference pref = findPreference(getString(R.string.pref_enabled_key));
    pref.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            boolean enabled = (Boolean) newValue;
            String enableStr = (enabled ? ManagePreferences.enableMsgType() : "");
            SmsPopupUtils.enableSMSPopup(SmsPopupConfigActivity.this, enableStr);
            CadPageWidget.update(SmsPopupConfigActivity.this);
            return true;
          }
        });
    pref = findPreference(getString(R.string.pref_enable_msg_type_key));
    pref.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            SmsPopupUtils.enableSMSPopup(SmsPopupConfigActivity.this, (String) newValue);
            return true;
          }
        });

    // Two other preferences should update the widget display
    pref = findPreference(getString(R.string.pref_notif_enabled_key));
    pref.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            CadPageWidget.update(SmsPopupConfigActivity.this);
            return true;
          }
        });
    pref = findPreference(getString(R.string.pref_popup_enabled_key));
    pref.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            CadPageWidget.update(SmsPopupConfigActivity.this);
            return true;
          }
        });

    // Set the version number in the about dialog preference
    final DialogPreference aboutPref =
        (DialogPreference) findPreference(getString(R.string.pref_about_key));
    aboutPref.setDialogTitle(CadPageApplication.getNameVersion());
    aboutPref.setDialogLayoutResource(R.layout.about);

    // Set up the payment status tracking screens
    Preference donate = (Preference) findPreference(getString(R.string.pref_payment_status_key));
    MainDonateEvent.instance().setPreference(this, donate);

    // Set up the two location preference screens
    Preference descPreference = findPreference(getString(R.string.pref_loc_desc_key));
    LocationManager locMgr = new LocationManager(this, descPreference);
    setupLocationMenu(R.string.pref_location_tree_key, false, locMgr);
    setupLocationMenu(R.string.pref_location_mtree_key, true, locMgr);
    locMgr.updateDisplay();

    // The location, filter override checkbox, and filter edit box have a complex
    // relationship.  The override checkbox is enabled only when the location parser
    // has a default parser to override.  If it doesn't then it is disabled by forced
    // to true.  The filter is enabled when the override box is checked, whether it
    // is enabled or not.  We have to do this ourselves because the Android dependency
    // logic considers the value to be false if it isn't enabled.

    // On top of all that, the general alert box is enabled only if the current
    // parser has a default filter OR a user filter has been specified

    genAlertPref = (CheckBoxPreference) findPreference(getString(R.string.pref_gen_alert_key));
    filterPref =
        (net.anei.cadpage.preferences.EditTextPreference)
            findPreference(getString(R.string.pref_filter_key));
    filterPref.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            String filter = (String) newValue;
            genAlertPref.setEnabled(filter.length() > 1 || parserFilter.length() > 0);
            return true;
          }
        });
    filterPref.setDialogClosedListener(
        new OnDialogClosedListener() {
          @Override
          public void onDialogClosed(boolean positiveResult) {
            if (positiveResult) {
              if ("General".equals(saveLocation)) {
                DonationManager.instance().reset();
                MainDonateEvent.instance().refreshStatus();
              }
            }
          }
        });

    overrideFilterPref =
        (CheckBoxPreference) findPreference(getString(R.string.pref_override_filter_key));
    filterPref.setEnabled(overrideFilterPref.isChecked());
    overrideFilterPref.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            filterPref.setEnabled((Boolean) newValue);
            return true;
          }
        });

    adjustLocationChange(ManagePreferences.location(), false);
    locMgr.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            adjustLocationChange((String) newValue, true);
            return true;
          }
        });

    // Have to play some games with the override default settings
    // If the override defaults is turned on, enable the default city and state items
    // If it is turned off, force the default city and state to the current parser
    // defaults and disable them.
    overrideDefaultPref =
        (CheckBoxPreference) findPreference(getString(R.string.pref_override_default_key));
    defCityPref = (EditTextPreference) findPreference(getString(R.string.pref_defcity_key));
    defStatePref = (EditTextPreference) findPreference(getString(R.string.pref_defstate_key));

    overrideDefaultPref =
        (CheckBoxPreference) findPreference(getString(R.string.pref_override_default_key));
    overrideDefaultPref.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            boolean value = ((Boolean) newValue).booleanValue();
            if (!value) {
              defCityPref.setText(parserDefCity);
              defCityPref.refreshSummary();
              defStatePref.setText(parserDefState);
              defStatePref.refreshSummary();
            }
            defCityPref.setEnabled(value);
            defStatePref.setEnabled(value);
            return true;
          }
        });

    // Make an initial call to our preference change listener to set up the
    // correct default summary displays
    overrideDefaultPref
        .getOnPreferenceChangeListener()
        .onPreferenceChange(overrideDefaultPref, ManagePreferences.overrideDefaults());

    // Set up Scanner channel selection preference
    scannerPref = findPreference(getString(R.string.pref_scanner_channel_key));
    if (scannerPref != null) {
      String channel = ManagePreferences.scannerChannel();
      scannerPref.setSummary(channel);
      scannerPref.setOnPreferenceClickListener(
          new OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference pref) {

              // When clicked, ask the scanner app to select a favorite channel
              Intent intent = new Intent("com.scannerradio.intent.action.ACTION_PICK");
              try {
                startActivityForResult(intent, REQ_SCANNER_CHANNEL);
              } catch (ActivityNotFoundException ex) {

                // Scanner radio either isn't installed, or isn't responding to the ACTION_PICK
                // request.  Check the package manager to which, if any, are currently installed
                PackageManager pkgMgr = getPackageManager();
                String pkgName = "com.scannerradio_pro";
                boolean installed = false;
                try {
                  pkgMgr.getPackageInfo(pkgName, 0);
                  installed = true;
                } catch (PackageManager.NameNotFoundException ex2) {
                }
                if (!installed) {
                  pkgName = "com.scannerradio";
                  try {
                    pkgMgr.getPackageInfo(pkgName, 0);
                    installed = true;
                  } catch (PackageManager.NameNotFoundException ex2) {
                  }
                }

                // OK, show a dialog box asking if they want to install Scanner Radio
                final String pkgName2 = pkgName;
                new AlertDialog.Builder(SmsPopupConfigActivity.this)
                    .setMessage(
                        installed ? R.string.scanner_not_current : R.string.scanner_not_installed)
                    .setPositiveButton(
                        R.string.donate_btn_yes,
                        new DialogInterface.OnClickListener() {
                          @Override
                          public void onClick(DialogInterface dialog, int which) {
                            Intent intent =
                                new Intent(
                                    Intent.ACTION_VIEW,
                                    Uri.parse("market://details?id=" + pkgName2));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            SmsPopupConfigActivity.this.startActivity(intent);
                          }
                        })
                    .setNegativeButton(R.string.donate_btn_no, null)
                    .create()
                    .show();
              }
              return true;
            }
          });
    }

    // Email developer response
    Preference emailPref = findPreference(getString(R.string.pref_email_key));
    emailPref.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          @Override
          public boolean onPreferenceClick(Preference preference) {
            EmailDeveloperActivity.sendGeneralEmail(SmsPopupConfigActivity.this);
            return true;
          }
        });

    // Set up C2DM vendor preference screen
    PreferenceScreen vendorPref =
        (PreferenceScreen) findPreference(getString(R.string.pref_direct_paging_key));
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO
        || DonationManager.instance().isFreeVersion()) {
      vendorPref.setEnabled(false);
    } else {
      VendorManager.instance().setupPreference(this, vendorPref);
    }

    // If free version, switch release notes text to free release notes text
    if (DonationManager.instance().isFreeVersion()) {
      DialogPreference dlg =
          (DialogPreference) findPreference(getString(R.string.pref_releasenotes_key));
      dlg.setDialogMessage(R.string.free_release_text);
    }
    // Add developer dialog preference if appropriate
    DeveloperToolsManager.instance().addPreference(this, getPreferenceScreen());
  }
 @Override
 protected void onDestroy() {
   MainDonateEvent.instance().setPreference(null, null);
   super.onDestroy();
 }
  /*
   * Populate all the main SMS/MMS views with content from the actual
   * SmsMmsMessage
   */
  private void populateViews(SmsMmsMessage newMessage) {

    // Store message
    message = newMessage;

    // Set up regular button list
    optManager = new MsgOptionManager(this, message);
    optManager.setupButtons(
        (ViewGroup) findViewById(R.id.RespButtonLayout),
        (ViewGroup) findViewById(R.id.RegButtonLayout));

    info = message.getInfo();

    // Hook the donate status button with the current donation status
    MainDonateEvent.instance().setButton(this, donateStatusBtn, newMessage);

    // Update Icon to indicate direct paging source
    int resIcon = VendorManager.instance().getVendorIconId(message.getVendorCode());
    if (resIcon <= 0) resIcon = R.drawable.ic_launcher;
    fromImage.setImageResource(resIcon);

    // Update TextView that contains the timestamp for the incoming message
    String headerText;
    String timeStamp = message.getFormattedTimestamp(this).toString();
    if (ManagePreferences.showSource()) {
      String source = "";
      if (info != null) source = info.getSource();
      if (source.length() == 0) source = message.getLocation();
      headerText = getString(R.string.src_text_at, source, timeStamp); //
    } else {
      headerText = getString(R.string.new_text_at, timeStamp);
    }

    String detailText;

    // Special case if we have no parsed information (which is just about impossible)
    if (info == null) {
      detailText = message.getTitle();
    }

    // Otherwise do things normally
    else {

      // Set the from, message and header views
      StringBuilder sb = new StringBuilder(info.getTitle());
      fromTV.setText(sb.toString());
      if (info.noCall()) fromTV.setMaxLines(2);
      sb = new StringBuilder();
      if (info.getPlace().length() > 0) {
        sb.append(info.getPlace());
        sb.append('\n');
      }
      String addr = info.getAddress();
      String apt = info.getApt();
      if (apt.length() > 0) {
        if (addr.length() > 0) addr = addr + ' ';
        addr = addr + getString(R.string.apt_label) + apt;
      }
      if (addr.length() > 0) {
        sb.append(addr);
        sb.append('\n');
      }
      String city = info.getCity();
      String st = info.getState();
      if (st.length() > 0) {
        if (city.length() > 0) city += ", ";
        city += st;
      }
      if (city.length() > 0) {
        sb.append(city);
        sb.append('\n');
      }
      if (info.getCross().length() > 0) {
        sb.append(getString(R.string.cross_label));
        sb.append(info.getCross());
        sb.append('\n');
      }
      if (info.getMap().length() > 0) {
        sb.append(getString(R.string.map_label));
        sb.append(info.getMap());
        sb.append('\n');
      }
      if (info.getBox().length() > 0) {
        sb.append(getString(R.string.box_label));
        sb.append(info.getBox());
        sb.append('\n');
      }
      if (info.getUnit().length() > 0) {
        sb.append(getString(R.string.units_label));
        sb.append(info.getUnit());
        sb.append('\n');
      }
      if (ManagePreferences.showPersonal()) {
        if (info.getName().length() > 0) {
          sb.append(getString(R.string.name_label));
          sb.append(info.getName());
          sb.append('\n');
        }
        if (info.getPhone().length() > 0) {
          sb.append(getString(R.string.phone_label));
          sb.append(info.getPhone());
          sb.append('\n');
        }
      }
      if (info.getChannel().length() > 0) {
        sb.append(getString(R.string.channel_label));
        sb.append(info.getChannel());
        sb.append('\n');
      }
      if (info.getSupp().length() > 0) {
        sb.append(info.getSupp());
        sb.append('\n');
      }
      if (info.getCallId().length() > 0) {
        sb.append(getString(R.string.call_id_label));
        sb.append(info.getCallId());
        sb.append('\n');
      }

      // Remove trailing \n
      int len = sb.length();
      if (len > 0) sb.setLength(len - 1);
      detailText = sb.toString();
    }
    messageReceivedTV.setText(headerText);
    messageTV.setText(detailText);

    // There used to be a call to myFinish() that was invoked if this method was
    // passed a message that was not a CAD page.  I am about as certain as I can
    // possibly be that this is no longer possible, which is why this call no
    // longer exists.  But the comment remains as a possible clue if someone
    // should discover I was wrong.

    // Will add a Database method in the future.
    // storeFileMessage();

  } // end of function
 @Override
 protected void onDestroy() {
   MainDonateEvent.instance().setButton(null, null, null);
   ManagePreferences.releasePermissionManager(permMgr);
   super.onDestroy();
 }