private Location getBaseLocation(Context context) {
   String sLat = XRestriction.getSetting(this, context, XRestriction.cSettingLatitude, "", true);
   String sLon = XRestriction.getSetting(this, context, XRestriction.cSettingLongitude, "", true);
   if (sLat.equals("") || sLon.equals("")) return null;
   Location location = new Location("");
   location.setLatitude(Float.parseFloat(sLat));
   location.setLongitude(Float.parseFloat(sLon));
   return location;
 }
 private void optionSwitchTheme() {
   String sTheme = XRestriction.getSetting(null, this, XRestriction.cSettingTheme, null, false);
   int themeId = (sTheme == null ? android.R.style.Theme_Holo_Light : Integer.parseInt(sTheme));
   if (themeId == android.R.style.Theme_Holo_Light)
     XRestriction.setSetting(
         null, this, XRestriction.cSettingTheme, Integer.toString(android.R.style.Theme_Holo));
   else
     XRestriction.setSetting(
         null,
         this,
         XRestriction.cSettingTheme,
         Integer.toString(android.R.style.Theme_Holo_Light));
   this.recreate();
 }
 @Override
 public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
   if (mAppAdapter != null) {
     String restrictionName = XRestriction.getRestrictions().get(pos);
     mAppAdapter.setRestrictionName(restrictionName);
   }
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set layout
    String sTheme = XRestriction.getSetting(null, this, XRestriction.cSettingTheme, null, false);
    mThemeId = (sTheme == null ? android.R.style.Theme_Holo_Light : Integer.parseInt(sTheme));
    setTheme(mThemeId);
    setContentView(R.layout.xmainlist);

    // Get localized restriction name
    List<String> listRestriction = XRestriction.getRestrictions();
    List<String> listLocalizedRestriction = new ArrayList<String>();
    for (String restrictionName : listRestriction)
      listLocalizedRestriction.add(XRestriction.getLocalizedName(this, restrictionName));

    // Build spinner adapter
    ArrayAdapter<String> spAdapter =
        new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
    spAdapter.addAll(listLocalizedRestriction);

    // Setup search
    final EditText etFilter = (EditText) findViewById(R.id.etFilter);
    etFilter.addTextChangedListener(
        new TextWatcher() {
          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (mAppAdapter != null) mAppAdapter.getFilter().filter(etFilter.getText().toString());
          }

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void afterTextChanged(Editable s) {}
        });

    // Setup spinner
    spRestriction = (Spinner) findViewById(R.id.spRestriction);
    spRestriction.setAdapter(spAdapter);
    spRestriction.setOnItemSelectedListener(this);

    // Handle help
    ImageView ivHelp = (ImageView) findViewById(R.id.ivHelp);
    ivHelp.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Dialog dialog = new Dialog(ActivityMain.this);
            dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
            dialog.setTitle(getString(R.string.help_application));
            dialog.setContentView(R.layout.xhelp);
            dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ic_launcher);
            dialog.setCancelable(true);
            dialog.show();
          }
        });

    // Start task to get app list
    AppListTask appListTask = new AppListTask();
    appListTask.execute(listRestriction.get(0));

    // Check environment
    checkRequirements();
  }
    @Override
    protected String doInBackground(File... params) {
      mFile = params[0];
      try {
        // Read XML
        FileInputStream fis = new FileInputStream(mFile);
        InputStreamReader isr = new InputStreamReader(fis);
        char[] inputBuffer = new char[fis.available()];
        isr.read(inputBuffer);
        String xml = new String(inputBuffer);
        isr.close();
        fis.close();

        // Prepare XML document
        InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(is);
        dom.getDocumentElement().normalize();

        // Process settings
        publishProgress(getString(R.string.menu_settings));
        NodeList sItems = dom.getElementsByTagName("Setting");
        for (int i = 0; i < sItems.getLength(); i++) {
          // Process package restriction
          Node entry = sItems.item(i);
          NamedNodeMap attrs = entry.getAttributes();
          String setting = attrs.getNamedItem("Name").getNodeValue();
          String value = attrs.getNamedItem("Value").getNodeValue();
          XRestriction.setSetting(null, ActivityMain.this, setting, value);
        }

        // Process restrictions
        Map<String, Map<String, List<String>>> mapPackage =
            new HashMap<String, Map<String, List<String>>>();
        NodeList rItems = dom.getElementsByTagName("Package");
        for (int i = 0; i < rItems.getLength(); i++) {
          // Process package restriction
          Node entry = rItems.item(i);
          NamedNodeMap attrs = entry.getAttributes();
          String packageName = attrs.getNamedItem("Name").getNodeValue();
          String restrictionName = attrs.getNamedItem("Restriction").getNodeValue();
          String methodName =
              (attrs.getNamedItem("Method") == null
                  ? null
                  : attrs.getNamedItem("Method").getNodeValue());

          // Map package restriction
          if (!mapPackage.containsKey(packageName))
            mapPackage.put(packageName, new HashMap<String, List<String>>());
          if (!mapPackage.get(packageName).containsKey(restrictionName))
            mapPackage.get(packageName).put(restrictionName, new ArrayList<String>());
          if (methodName != null) mapPackage.get(packageName).get(restrictionName).add(methodName);
        }

        // Process result
        for (String packageName : mapPackage.keySet()) {
          try {
            publishProgress(packageName);

            // Get uid
            int uid = getPackageManager().getPackageInfo(packageName, 0).applicationInfo.uid;

            // Reset existing restrictions
            XRestriction.deleteRestrictions(ActivityMain.this, uid);

            // Set imported restrictions
            for (String restrictionName : mapPackage.get(packageName).keySet()) {
              XRestriction.setRestricted(null, ActivityMain.this, uid, restrictionName, null, true);
              for (String methodName : mapPackage.get(packageName).get(restrictionName))
                XRestriction.setRestricted(
                    null, ActivityMain.this, uid, restrictionName, methodName, false);
            }
          } catch (NameNotFoundException ex) {
            XUtil.log(null, Log.WARN, "Not found package=" + packageName);
          }
        }

        // Display message
        return getString(R.string.msg_done);
      } catch (Throwable ex) {
        XUtil.bug(null, ex);
        return ex.toString();
      }
    }
  private void optionSettings() {
    // Build dialog
    final Dialog dlgSettings = new Dialog(this);
    dlgSettings.requestWindowFeature(Window.FEATURE_LEFT_ICON);
    dlgSettings.setTitle(getString(R.string.app_name));
    dlgSettings.setContentView(R.layout.xsettings);
    dlgSettings.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ic_launcher);

    // Reference controls
    final CheckBox cbSettings = (CheckBox) dlgSettings.findViewById(R.id.cbExpert);
    final EditText etLat = (EditText) dlgSettings.findViewById(R.id.etLat);
    final EditText etLon = (EditText) dlgSettings.findViewById(R.id.etLon);
    final EditText etMac = (EditText) dlgSettings.findViewById(R.id.etMac);
    Button btnOk = (Button) dlgSettings.findViewById(R.id.btnOk);

    // Set current values
    String sExpert =
        XRestriction.getSetting(
            null, ActivityMain.this, XRestriction.cSettingExpert, Boolean.FALSE.toString(), false);
    final boolean expert = Boolean.parseBoolean(sExpert);
    cbSettings.setChecked(expert);
    etLat.setText(
        XRestriction.getSetting(null, ActivityMain.this, XRestriction.cSettingLatitude, "", false));
    etLon.setText(
        XRestriction.getSetting(
            null, ActivityMain.this, XRestriction.cSettingLongitude, "", false));
    etMac.setText(
        XRestriction.getSetting(
            null,
            ActivityMain.this,
            XRestriction.cSettingMac,
            XRestriction.getDefacedMac(),
            false));

    // Wait for OK
    btnOk.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            // Set expert mode
            XRestriction.setSetting(
                null,
                ActivityMain.this,
                XRestriction.cSettingExpert,
                Boolean.toString(cbSettings.isChecked()));
            if (expert != cbSettings.isChecked()) {
              // Start task to get app list
              List<String> listRestriction = XRestriction.getRestrictions();
              String restrictionName = listRestriction.get(0);
              AppListTask appListTask = new AppListTask();
              appListTask.execute(restrictionName);
            }

            // Set location
            try {
              float lat = Float.parseFloat(etLat.getText().toString().replace(',', '.'));
              float lon = Float.parseFloat(etLon.getText().toString().replace(',', '.'));
              if (lat < -90 || lat > 90 || lon < -180 || lon > 180)
                throw new InvalidParameterException();

              XRestriction.setSetting(
                  null, ActivityMain.this, XRestriction.cSettingLatitude, Float.toString(lat));
              XRestriction.setSetting(
                  null, ActivityMain.this, XRestriction.cSettingLongitude, Float.toString(lon));

            } catch (Throwable ex) {
              XRestriction.setSetting(null, ActivityMain.this, XRestriction.cSettingLatitude, "");
              XRestriction.setSetting(null, ActivityMain.this, XRestriction.cSettingLongitude, "");
            }

            // Set MAC address
            XRestriction.setSetting(
                null, ActivityMain.this, XRestriction.cSettingMac, etMac.getText().toString());

            // Done
            dlgSettings.dismiss();
          }
        });

    dlgSettings.setCancelable(true);
    dlgSettings.show();
  }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View row = inflater.inflate(R.layout.xmainentry, parent, false);
      LinearLayout llIcon = (LinearLayout) row.findViewById(R.id.llIcon);
      ImageView imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
      ImageView imgInternet = (ImageView) row.findViewById(R.id.imgInternet);
      ImageView imgUsed = (ImageView) row.findViewById(R.id.imgUsed);
      final CheckedTextView ctvApp = (CheckedTextView) row.findViewById(R.id.ctvName);

      // Get entry
      final XApplicationInfo xAppInfo = getItem(position);

      // Set background color
      if (xAppInfo.getIsSystem())
        if (mThemeId == android.R.style.Theme_Holo_Light)
          row.setBackgroundColor(Color.parseColor("#FFFDD0"));
        else row.setBackgroundColor(Color.DKGRAY);

      // Click handler
      llIcon.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              Intent intentSettings = new Intent(view.getContext(), ActivityApp.class);
              intentSettings.putExtra(ActivityApp.cPackageName, xAppInfo.getPackageName());
              intentSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              view.getContext().startActivity(intentSettings);
            }
          });

      // Set icon
      imgIcon.setImageDrawable(xAppInfo.getDrawable());

      // Set title
      ctvApp.setText(xAppInfo.toString());

      // Check if internet access
      imgInternet.setVisibility(xAppInfo.hasInternet() ? View.VISIBLE : View.INVISIBLE);

      // Check if used
      boolean used =
          XRestriction.isUsed(row.getContext(), xAppInfo.getUid(), mRestrictionName, null);
      ctvApp.setTypeface(null, used ? Typeface.BOLD_ITALIC : Typeface.NORMAL);
      imgUsed.setVisibility(used ? View.VISIBLE : View.INVISIBLE);

      // Display restriction
      boolean restricted =
          XRestriction.getRestricted(
              null, row.getContext(), xAppInfo.getUid(), mRestrictionName, null, false, false);
      ctvApp.setChecked(restricted);

      // Listen for restriction changes
      ctvApp.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              boolean restricted =
                  XRestriction.getRestricted(
                      null,
                      view.getContext(),
                      xAppInfo.getUid(),
                      mRestrictionName,
                      null,
                      false,
                      false);
              restricted = !restricted;
              ctvApp.setChecked(restricted);
              XRestriction.setRestricted(
                  null, view.getContext(), xAppInfo.getUid(), mRestrictionName, null, restricted);
            }
          });

      row.refreshDrawableState();
      return row;
    }