Example usage for android.widget PopupMenu setOnMenuItemClickListener

List of usage examples for android.widget PopupMenu setOnMenuItemClickListener

Introduction

In this page you can find the example usage for android.widget PopupMenu setOnMenuItemClickListener.

Prototype

public void setOnMenuItemClickListener(OnMenuItemClickListener listener) 

Source Link

Document

Sets a listener that will be notified when the user selects an item from the menu.

Usage

From source file:com.master.metehan.filtereagle.AdapterRule.java

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // Get rule/*from w  w w.  jav a  2 s.  c  om*/
    final Rule rule = listFiltered.get(position);

    // Handle expanding/collapsing
    holder.llApplication.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rule.expanded = !rule.expanded;
            notifyItemChanged(position);
        }
    });

    // Show if non default rules
    holder.itemView.setBackgroundColor(rule.changed ? colorChanged : Color.TRANSPARENT);

    // Show expand/collapse indicator
    holder.ivExpander.setImageLevel(rule.expanded ? 1 : 0);

    // Show application icon
    if (rule.info.applicationInfo == null || rule.info.applicationInfo.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(holder.ivIcon);
    else {
        Uri uri = Uri
                .parse("android.resource://" + rule.info.packageName + "/" + rule.info.applicationInfo.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(holder.ivIcon);
    }

    // Show application label
    holder.tvName.setText(rule.name);
    holder.tvDescription.setVisibility(rule.description == null ? View.GONE : View.VISIBLE);
    holder.tvDescription.setText(rule.description);

    // Show application state
    int color = rule.system ? colorOff : colorText;
    if (!rule.internet || !rule.enabled)
        color = Color.argb(128, Color.red(color), Color.green(color), Color.blue(color));
    holder.tvName.setTextColor(color);

    // Show rule count
    new AsyncTask<Object, Object, Long>() {
        @Override
        protected void onPreExecute() {
            holder.tvHosts.setVisibility(View.GONE);
        }

        @Override
        protected Long doInBackground(Object... objects) {
            return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid);
        }

        @Override
        protected void onPostExecute(Long rules) {
            if (rules > 0) {
                holder.tvHosts.setVisibility(View.VISIBLE);
                holder.tvHosts.setText(Long.toString(rules));
            }
        }
    }.execute();

    // Wi-Fi settings
    holder.cbWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.cbWifi.setOnCheckedChangeListener(null);
    holder.cbWifi.setChecked(rule.wifi_blocked);
    holder.cbWifi.setEnabled(rule.apply);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbWifi));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.wifi_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.wifi_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenWifi.setEnabled(rule.apply);
    holder.ivScreenWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.ivScreenWifi.setVisibility(rule.screen_wifi && rule.wifi_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenWifi.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    // Mobile settings
    holder.cbOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.cbOther.setOnCheckedChangeListener(null);
    holder.cbOther.setChecked(rule.other_blocked);
    holder.cbOther.setEnabled(rule.apply);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbOther));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.other_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.other_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenOther.setEnabled(rule.apply);
    holder.ivScreenOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.ivScreenOther.setVisibility(rule.screen_other && rule.other_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenOther.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    holder.tvRoaming.setTextColor(rule.apply ? colorOff : colorGrayed);
    holder.tvRoaming.setAlpha(otherActive ? 1 : 0.5f);
    holder.tvRoaming.setVisibility(
            rule.roaming && (!rule.other_blocked || rule.screen_other) ? View.VISIBLE : View.INVISIBLE);

    // Expanded configuration section
    holder.llConfiguration.setVisibility(rule.expanded ? View.VISIBLE : View.GONE);

    // Show application details
    holder.tvUid
            .setText(rule.info.applicationInfo == null ? "?" : Integer.toString(rule.info.applicationInfo.uid));
    holder.tvPackage.setText(rule.info.packageName);
    holder.tvVersion.setText(rule.info.versionName + '/' + rule.info.versionCode);

    // Show application state
    holder.tvDisabled.setVisibility(rule.enabled ? View.GONE : View.VISIBLE);
    holder.tvInternet.setVisibility(rule.internet ? View.GONE : View.VISIBLE);

    // Apply
    holder.cbApply
            .setVisibility(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? View.GONE : View.VISIBLE);
    holder.cbApply.setEnabled(rule.pkg);
    holder.cbApply.setOnCheckedChangeListener(null);
    holder.cbApply.setChecked(rule.apply);
    holder.cbApply.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.apply = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show related
    holder.btnRelated.setVisibility(rule.relateduids ? View.VISIBLE : View.GONE);
    holder.btnRelated.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent main = new Intent(context, ActivityMain.class);
            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(rule.info.applicationInfo.uid));
            context.startActivity(main);
        }
    });

    // Launch application settings
    final Intent settings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    settings.setData(Uri.parse("package:" + rule.info.packageName));
    holder.ibSettings.setVisibility(
            settings.resolveActivity(context.getPackageManager()) == null ? View.GONE : View.VISIBLE);
    holder.ibSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(settings);
        }
    });

    // Launch application
    holder.ibLaunch.setVisibility(rule.intent == null ? View.GONE : View.VISIBLE);
    holder.ibLaunch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(rule.intent);
        }
    });

    // Show Wi-Fi screen on condition
    holder.cbScreenWifi.setOnCheckedChangeListener(null);
    holder.cbScreenWifi.setChecked(rule.screen_wifi);
    holder.cbScreenWifi.setEnabled(rule.wifi_blocked && rule.apply);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivWifiLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    holder.cbScreenWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_wifi = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    // Show mobile screen on condition
    holder.cbScreenOther.setOnCheckedChangeListener(null);
    holder.cbScreenOther.setChecked(rule.screen_other);
    holder.cbScreenOther.setEnabled(rule.other_blocked && rule.apply);

    holder.cbScreenOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_other = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show roaming condition
    holder.cbRoaming.setOnCheckedChangeListener(null);
    holder.cbRoaming.setChecked(rule.roaming);
    holder.cbRoaming.setEnabled((!rule.other_blocked || rule.screen_other) && rule.apply);

    holder.cbRoaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.roaming = isChecked;
            updateRule(rule, true, listAll);

            // Request permissions
            if (isChecked && !Util.hasPhoneStatePermission(context))
                context.requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE },
                        ActivityMain.REQUEST_ROAMING);
        }
    });

    // Reset rule
    holder.btnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_clear_rules, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    holder.cbApply.setChecked(true);
                    holder.cbWifi.setChecked(rule.wifi_default);
                    holder.cbOther.setChecked(rule.other_default);
                    holder.cbScreenWifi.setChecked(rule.screen_wifi_default);
                    holder.cbScreenOther.setChecked(rule.screen_other_default);
                    holder.cbRoaming.setChecked(rule.roaming_default);
                }
            });
        }
    });

    // Show access rules
    if (rule.expanded) {
        // Access the database when expanded only
        final AdapterAccess badapter = new AdapterAccess(context,
                DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid));
        if (filter)
            holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int bposition, long bid) {
                    PackageManager pm = context.getPackageManager();
                    Cursor cursor = (Cursor) badapter.getItem(bposition);
                    final long id = cursor.getLong(cursor.getColumnIndex("ID"));
                    int version = cursor.getInt(cursor.getColumnIndex("version"));
                    int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
                    String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
                    int dport = cursor.getInt(cursor.getColumnIndex("dport"));
                    long time = cursor.getLong(cursor.getColumnIndex("time"));
                    int block = cursor.getInt(cursor.getColumnIndex("block"));

                    PopupMenu popup = new PopupMenu(context, context.findViewById(R.id.vwPopupAnchor));
                    popup.inflate(R.menu.access);

                    popup.getMenu().findItem(R.id.menu_host)
                            .setTitle(Util.getProtocolName(protocol, version, false) + " " + daddr
                                    + (dport > 0 ? "/" + dport : ""));

                    // Whois
                    final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://www.tcpiputils.com/whois-lookup/" + daddr));
                    if (pm.resolveActivity(lookupIP, 0) == null)
                        popup.getMenu().removeItem(R.id.menu_whois);
                    else
                        popup.getMenu().findItem(R.id.menu_whois)
                                .setTitle(context.getString(R.string.title_log_whois, daddr));

                    // Lookup port
                    final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://www.speedguide.net/port.php?port=" + dport));
                    if (dport <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                        popup.getMenu().removeItem(R.id.menu_port);
                    else
                        popup.getMenu().findItem(R.id.menu_port)
                                .setTitle(context.getString(R.string.title_log_port, dport));

                    popup.getMenu().findItem(R.id.menu_time)
                            .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

                    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {
                            switch (menuItem.getItemId()) {
                            case R.id.menu_whois:
                                context.startActivity(lookupIP);
                                return true;

                            case R.id.menu_port:
                                context.startActivity(lookupPort);
                                return true;

                            case R.id.menu_allow:
                                if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) {
                                    DatabaseHelper.getInstance(context).setAccess(id, 0);
                                    ServiceSinkhole.reload("allow host", context);
                                } else
                                    context.startActivity(new Intent(context, ActivityPro.class));
                                return true;

                            case R.id.menu_block:
                                if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) {
                                    DatabaseHelper.getInstance(context).setAccess(id, 1);
                                    ServiceSinkhole.reload("block host", context);
                                } else
                                    context.startActivity(new Intent(context, ActivityPro.class));
                                return true;

                            case R.id.menu_reset:
                                DatabaseHelper.getInstance(context).setAccess(id, -1);
                                ServiceSinkhole.reload("reset host", context);
                                return true;
                            }
                            return false;
                        }
                    });

                    if (block == 0)
                        popup.getMenu().removeItem(R.id.menu_allow);
                    else if (block == 1)
                        popup.getMenu().removeItem(R.id.menu_block);

                    popup.show();
                }
            });
        else
            holder.lvAccess.setOnItemClickListener(null);

        holder.lvAccess.setAdapter(badapter);
    } else {
        holder.lvAccess.setAdapter(null);
        holder.lvAccess.setOnItemClickListener(null);
    }

    // Show logging is disabled
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean log_app = prefs.getBoolean("log_app", false);
    holder.tvNolog.setVisibility(log_app ? View.GONE : View.VISIBLE);
    holder.tvNolog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show disable access notifications setting
    holder.cbNotify.setOnCheckedChangeListener(null);
    holder.cbNotify.setEnabled(prefs.getBoolean("notify_access", false) && rule.apply);
    holder.cbNotify.setChecked(rule.notify);
    holder.cbNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.notify = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Clear access log
    holder.btnClearAccess.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid, true);
                    if (rv != null)
                        rv.scrollToPosition(position);
                }
            });
        }
    });

    // Show traffic statistics
    holder.tvStatistics.setText(context.getString(R.string.msg_mbday, rule.upspeed, rule.downspeed));
}

From source file:com.zhengde163.netguard.AdapterRule.java

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // Get rule//from  ww w. j a  v a  2s . c  o m
    final Rule rule = listFiltered.get(position);

    // Handle expanding/collapsing
    holder.llApplication.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rule.expanded = !rule.expanded;
            notifyItemChanged(position);
        }
    });

    holder.ivExpander.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rule.expanded = !rule.expanded;
            notifyItemChanged(position);
        }
    });

    // Show if non default rules
    holder.itemView.setBackgroundColor(rule.changed ? colorChanged : Color.TRANSPARENT);

    // Show expand/collapse indicator
    holder.ivExpander.setImageLevel(rule.expanded ? 1 : 0);

    // Show application icon
    if (rule.info.applicationInfo == null || rule.info.applicationInfo.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(holder.ivIcon);
    else {
        Uri uri = Uri
                .parse("android.resource://" + rule.info.packageName + "/" + rule.info.applicationInfo.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(holder.ivIcon);
    }

    // Show application label
    holder.tvName.setText(rule.name);
    holder.tvDescription.setVisibility(rule.description == null ? View.GONE : View.VISIBLE);
    holder.tvDescription.setText(rule.description);

    // Show application state
    int color = rule.system ? colorOff : colorText;
    if (!rule.internet || !rule.enabled)
        color = Color.argb(128, Color.red(color), Color.green(color), Color.blue(color));
    holder.tvName.setTextColor(color);

    // Show rule count
    new AsyncTask<Object, Object, Long>() {
        @Override
        protected void onPreExecute() {
            holder.tvHosts.setVisibility(View.GONE);
        }

        @Override
        protected Long doInBackground(Object... objects) {
            return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid);
        }

        @Override
        protected void onPostExecute(Long rules) {
            if (rules > 0) {
                holder.tvHosts.setVisibility(View.VISIBLE);
                holder.tvHosts.setText(Long.toString(rules));
            }
        }
    }.execute();

    // Wi-Fi settings
    holder.cbWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.cbWifi.setOnCheckedChangeListener(null);
    holder.cbWifi.setChecked(rule.wifi_blocked);
    holder.cbWifi.setEnabled(rule.apply);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbWifi));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.wifi_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.wifi_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenWifi.setEnabled(rule.apply);
    holder.ivScreenWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.ivScreenWifi.setVisibility(rule.screen_wifi && rule.wifi_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenWifi.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    // Mobile settings
    holder.cbOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.cbOther.setOnCheckedChangeListener(null);
    holder.cbOther.setChecked(rule.other_blocked);
    holder.cbOther.setEnabled(rule.apply);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbOther));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.other_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.other_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenOther.setEnabled(rule.apply);
    holder.ivScreenOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.ivScreenOther.setVisibility(rule.screen_other && rule.other_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenOther.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    holder.tvRoaming.setTextColor(rule.apply ? colorOff : colorGrayed);
    holder.tvRoaming.setAlpha(otherActive ? 1 : 0.5f);
    holder.tvRoaming.setVisibility(
            rule.roaming && (!rule.other_blocked || rule.screen_other) ? View.VISIBLE : View.INVISIBLE);

    // Expanded configuration section
    holder.llConfiguration.setVisibility(rule.expanded ? View.VISIBLE : View.GONE);

    // Show application details
    holder.tvUid.setText(rule.info.applicationInfo == null ? "?"
            : "uid : " + Integer.toString(rule.info.applicationInfo.uid));
    holder.tvPackage.setText("??? : " + rule.info.packageName);
    holder.tvVersion.setText("? : " + rule.info.versionName + '/' + rule.info.versionCode);

    // Show application state
    holder.tvDisabled.setVisibility(rule.enabled ? View.GONE : View.VISIBLE);
    holder.tvInternet.setVisibility(rule.internet ? View.GONE : View.VISIBLE);

    // Apply
    holder.cbApply
            .setVisibility(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? View.GONE : View.VISIBLE);
    holder.cbApply.setEnabled(rule.pkg);
    holder.cbApply.setOnCheckedChangeListener(null);
    holder.cbApply.setChecked(rule.apply);
    holder.cbApply.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.apply = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show related
    holder.btnRelated.setVisibility(rule.relateduids ? View.VISIBLE : View.GONE);
    holder.btnRelated.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent main = new Intent(context, ActivityMain.class);
            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(rule.info.applicationInfo.uid));
            context.startActivity(main);
        }
    });

    // Launch application settings
    final Intent settings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    settings.setData(Uri.parse("package:" + rule.info.packageName));
    holder.ibSettings.setVisibility(
            settings.resolveActivity(context.getPackageManager()) == null ? View.GONE : View.VISIBLE);
    holder.ibSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(settings);
        }
    });

    // Launch application
    holder.ibLaunch.setVisibility(rule.intent == null ? View.GONE : View.VISIBLE);
    holder.ibLaunch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(rule.intent);
        }
    });

    // Show Wi-Fi screen on condition
    holder.cbScreenWifi.setOnCheckedChangeListener(null);
    holder.cbScreenWifi.setChecked(rule.screen_wifi);
    holder.cbScreenWifi.setEnabled(rule.wifi_blocked && rule.apply);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivWifiLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    holder.cbScreenWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_wifi = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    // Show mobile screen on condition
    holder.cbScreenOther.setOnCheckedChangeListener(null);
    holder.cbScreenOther.setChecked(rule.screen_other);
    holder.cbScreenOther.setEnabled(rule.other_blocked && rule.apply);

    holder.cbScreenOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_other = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show roaming condition
    holder.cbRoaming.setOnCheckedChangeListener(null);
    holder.cbRoaming.setChecked(rule.roaming);
    holder.cbRoaming.setEnabled((!rule.other_blocked || rule.screen_other) && rule.apply);

    holder.cbRoaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.roaming = isChecked;
            updateRule(rule, true, listAll);

            // Request permissions
            if (isChecked && !Util.hasPhoneStatePermission(context))
                context.requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE },
                        ActivityMain.REQUEST_ROAMING);
        }
    });

    // Reset rule
    holder.btnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_clear_rules, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    holder.cbApply.setChecked(true);
                    holder.cbWifi.setChecked(rule.wifi_default);
                    holder.cbOther.setChecked(rule.other_default);
                    holder.cbScreenWifi.setChecked(rule.screen_wifi_default);
                    holder.cbScreenOther.setChecked(rule.screen_other_default);
                    holder.cbRoaming.setChecked(rule.roaming_default);
                }
            });
        }
    });

    // Show access rules
    if (rule.expanded) {
        // Access the database when expanded only
        final AdapterAccess badapter = new AdapterAccess(context,
                DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid));
        if (filter)
            holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int bposition, long bid) {
                    PackageManager pm = context.getPackageManager();
                    Cursor cursor = (Cursor) badapter.getItem(bposition);
                    final long id = cursor.getLong(cursor.getColumnIndex("ID"));
                    int version = cursor.getInt(cursor.getColumnIndex("version"));
                    int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
                    String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
                    int dport = cursor.getInt(cursor.getColumnIndex("dport"));
                    long time = cursor.getLong(cursor.getColumnIndex("time"));
                    int block = cursor.getInt(cursor.getColumnIndex("block"));

                    PopupMenu popup = new PopupMenu(context, context.findViewById(R.id.vwPopupAnchor));
                    popup.inflate(R.menu.access);

                    popup.getMenu().findItem(R.id.menu_host)
                            .setTitle(Util.getProtocolName(protocol, version, false) + " " + daddr
                                    + (dport > 0 ? "/" + dport : ""));

                    // Whois
                    final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://www.tcpiputils.com/whois-lookup/" + daddr));
                    if (pm.resolveActivity(lookupIP, 0) == null)
                        popup.getMenu().removeItem(R.id.menu_whois);
                    else
                        popup.getMenu().findItem(R.id.menu_whois)
                                .setTitle(context.getString(R.string.title_log_whois, daddr));

                    // Lookup port
                    final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://www.speedguide.net/port.php?port=" + dport));
                    if (dport <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                        popup.getMenu().removeItem(R.id.menu_port);
                    else
                        popup.getMenu().findItem(R.id.menu_port)
                                .setTitle(context.getString(R.string.title_log_port, dport));

                    popup.getMenu().findItem(R.id.menu_time)
                            .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

                    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {
                            switch (menuItem.getItemId()) {
                            case R.id.menu_whois:
                                context.startActivity(lookupIP);
                                return true;

                            case R.id.menu_port:
                                context.startActivity(lookupPort);
                                return true;

                            case R.id.menu_allow:
                                DatabaseHelper.getInstance(context).setAccess(id, 0);
                                ServiceSinkhole.reload("allow host", context);
                                return true;

                            case R.id.menu_block:
                                DatabaseHelper.getInstance(context).setAccess(id, 1);
                                ServiceSinkhole.reload("block host", context);
                                return true;

                            case R.id.menu_reset:
                                DatabaseHelper.getInstance(context).setAccess(id, -1);
                                ServiceSinkhole.reload("reset host", context);
                                return true;
                            }
                            return false;
                        }
                    });

                    if (block == 0)
                        popup.getMenu().removeItem(R.id.menu_allow);
                    else if (block == 1)
                        popup.getMenu().removeItem(R.id.menu_block);

                    popup.show();
                }
            });
        else
            holder.lvAccess.setOnItemClickListener(null);

        holder.lvAccess.setAdapter(badapter);
    } else {
        holder.lvAccess.setAdapter(null);
        holder.lvAccess.setOnItemClickListener(null);
    }

    // Show logging is disabled
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean log_app = prefs.getBoolean("log_app", false);
    holder.tvNolog.setVisibility(log_app ? View.GONE : View.VISIBLE);
    holder.tvNolog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show disable access notifications setting
    holder.cbNotify.setOnCheckedChangeListener(null);
    holder.cbNotify.setEnabled(prefs.getBoolean("notify_access", false) && rule.apply);
    holder.cbNotify.setChecked(rule.notify);
    holder.cbNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.notify = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Clear access log
    holder.btnClearAccess.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid, true);
                    if (rv != null)
                        rv.scrollToPosition(position);
                }
            });
        }
    });

    // Show traffic statistics
    holder.tvStatistics.setText(
            "?? : " + context.getString(R.string.msg_mbday, rule.upspeed, rule.downspeed));
}

From source file:com.simadanesh.isatis.ScreenSlideActivity.java

private void showfilterMenu() {
    View p = findViewById(R.id.anchorer);
    progressbar.setVisibility(View.GONE);

    final PopupMenu popup = new PopupMenu(this, p);
    //Inflating the Popup using xml file  
    popup.getMenuInflater().inflate(R.menu.filter, popup.getMenu());
    for (int i = 0; i < popup.getMenu().size(); i++) {
        MenuItem item = popup.getMenu().getItem(i);
        String countstr = "0";
        switch (item.getItemId()) {
        case R.id.filter_no_filter:
            countstr = countFilterNofilter();
            break;
        case R.id.filter_no_data:
            countstr = countFilterNodata();
            break;
        case R.id.filter_valid_reading:
            countstr = countFilterValid();
            break;
        case R.id.filter_hilow:
            countstr = countFilterHilow();
            break;
        case R.id.filter_maneh:
            countstr = countFilterManeh();

            break;
        case R.id.filter_inspection:
            countstr = countFilterInspection();
            break;
        case R.id.filter_register_field:
            countstr = countFilterRegisterField();
            break;
        case R.id.filter_not_register_field:
            countstr = countFilterRegisterNotField();
            break;

        }/* w  w w .  j  a  v a  2  s  . c o m*/
        item.setTitle(item.getTitle() + "\t" + countstr);
    }

    //registering popup with OnMenuItemClickListener  
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.filter_no_filter:
                filterNofilter();
                break;
            case R.id.filter_no_data:
                filterNodata();
                break;
            case R.id.filter_valid_reading:
                filterValid();
                break;
            case R.id.filter_hilow:
                filterHilow();
                break;
            case R.id.filter_maneh:
                //filterManeh();
                showManehMenu();
                break;
            case R.id.filter_inspection:
                filterInspection();
                break;
            case R.id.filter_register_field:
                filterRegisterField();
                break;
            case R.id.filter_not_register_field:
                filterRegisterNotField();
                break;

            }
            return true;
        }
    });

    final Handler handler1 = new Handler();
    progressbar.setVisibility(View.GONE);
    //android.R.attr.progressBarStyleLarge
    handler1.postDelayed(new Runnable() {
        @Override
        public void run() {
            popup.show();
        }
    }, 100);
}

From source file:android_network.hetnet.vpn_service.AdapterRule.java

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    // Get rule//  ww  w . ja v a2s .  c  om
    final Rule rule = listFiltered.get(position);

    // Handle expanding/collapsing
    holder.llApplication.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rule.expanded = !rule.expanded;
            notifyItemChanged(position);
        }
    });

    // Show if non default rules
    holder.itemView.setBackgroundColor(rule.changed ? colorChanged : Color.TRANSPARENT);

    // Show expand/collapse indicator
    holder.ivExpander.setImageLevel(rule.expanded ? 1 : 0);

    // Show application icon
    if (rule.info.applicationInfo == null || rule.info.applicationInfo.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(holder.ivIcon);
    else {
        Uri uri = Uri
                .parse("android.resource://" + rule.info.packageName + "/" + rule.info.applicationInfo.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(holder.ivIcon);
    }

    // Show application label
    holder.tvName.setText(rule.name);

    // Show application state
    int color = rule.system ? colorOff : colorText;
    if (!rule.internet || !rule.enabled)
        color = Color.argb(128, Color.red(color), Color.green(color), Color.blue(color));
    holder.tvName.setTextColor(color);

    // Show rule count
    new AsyncTask<Object, Object, Long>() {
        @Override
        protected void onPreExecute() {
            holder.tvHosts.setVisibility(View.GONE);
        }

        @Override
        protected Long doInBackground(Object... objects) {
            return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid);
        }

        @Override
        protected void onPostExecute(Long rules) {
            if (rules > 0) {
                holder.tvHosts.setVisibility(View.VISIBLE);
                holder.tvHosts.setText(Long.toString(rules));
            }
        }
    }.execute();

    boolean screen_on = prefs.getBoolean("screen_on", true);

    // Wi-Fi settings
    holder.cbWifi.setEnabled(rule.apply);
    holder.cbWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.cbWifi.setOnCheckedChangeListener(null);
    holder.cbWifi.setChecked(rule.wifi_blocked);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbWifi));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.wifi_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.wifi_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenWifi.setEnabled(rule.apply);
    holder.ivScreenWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.ivScreenWifi.setVisibility(rule.screen_wifi && rule.wifi_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenWifi.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    // Mobile settings
    holder.cbOther.setEnabled(rule.apply);
    holder.cbOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.cbOther.setOnCheckedChangeListener(null);
    holder.cbOther.setChecked(rule.other_blocked);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbOther));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.other_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.other_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenOther.setEnabled(rule.apply);
    holder.ivScreenOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.ivScreenOther.setVisibility(rule.screen_other && rule.other_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenOther.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    holder.tvRoaming.setTextColor(rule.apply ? colorOff : colorGrayed);
    holder.tvRoaming.setAlpha(otherActive ? 1 : 0.5f);
    holder.tvRoaming.setVisibility(
            rule.roaming && (!rule.other_blocked || rule.screen_other) ? View.VISIBLE : View.INVISIBLE);

    // Expanded configuration section
    holder.llConfiguration.setVisibility(rule.expanded ? View.VISIBLE : View.GONE);

    // Show application details
    holder.tvUid
            .setText(rule.info.applicationInfo == null ? "?" : Integer.toString(rule.info.applicationInfo.uid));
    holder.tvPackage.setText(rule.info.packageName);
    holder.tvVersion.setText(rule.info.versionName + '/' + rule.info.versionCode);
    holder.tvDescription.setVisibility(rule.description == null ? View.GONE : View.VISIBLE);
    holder.tvDescription.setText(rule.description);

    // Show application state
    holder.tvInternet.setVisibility(rule.internet ? View.GONE : View.VISIBLE);
    holder.tvDisabled.setVisibility(rule.enabled ? View.GONE : View.VISIBLE);

    // Show traffic statistics
    holder.tvStatistics
            .setVisibility(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? View.GONE : View.VISIBLE);
    holder.tvStatistics.setText(context.getString(R.string.msg_mbday, rule.upspeed, rule.downspeed));

    // Show related
    holder.btnRelated.setVisibility(rule.relateduids ? View.VISIBLE : View.GONE);
    holder.btnRelated.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent main = new Intent(context, MainActivity.class);
            main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(rule.info.applicationInfo.uid));
            context.startActivity(main);
        }
    });

    // Launch application settings
    holder.ibSettings.setVisibility(rule.settings == null ? View.GONE : View.VISIBLE);
    holder.ibSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(rule.settings);
        }
    });

    // Data saver
    holder.ibDatasaver.setVisibility(rule.datasaver == null ? View.GONE : View.VISIBLE);
    holder.ibDatasaver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(rule.datasaver);
        }
    });

    // Launch application
    holder.ibLaunch.setVisibility(rule.launch == null ? View.GONE : View.VISIBLE);
    holder.ibLaunch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(rule.launch);
        }
    });

    // Apply
    holder.cbApply.setEnabled(rule.pkg);
    holder.cbApply.setOnCheckedChangeListener(null);
    holder.cbApply.setChecked(rule.apply);
    holder.cbApply.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.apply = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show Wi-Fi screen on condition
    holder.llScreenWifi.setVisibility(screen_on ? View.VISIBLE : View.GONE);
    holder.cbScreenWifi.setEnabled(rule.wifi_blocked && rule.apply);
    holder.cbScreenWifi.setOnCheckedChangeListener(null);
    holder.cbScreenWifi.setChecked(rule.screen_wifi);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivWifiLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    holder.cbScreenWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_wifi = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    // Show mobile screen on condition
    holder.llScreenOther.setVisibility(screen_on ? View.VISIBLE : View.GONE);
    holder.cbScreenOther.setEnabled(rule.other_blocked && rule.apply);
    holder.cbScreenOther.setOnCheckedChangeListener(null);
    holder.cbScreenOther.setChecked(rule.screen_other);
    holder.cbScreenOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_other = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show roaming condition
    holder.cbRoaming.setEnabled((!rule.other_blocked || rule.screen_other) && rule.apply);
    holder.cbRoaming.setOnCheckedChangeListener(null);
    holder.cbRoaming.setChecked(rule.roaming);
    holder.cbRoaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.roaming = isChecked;
            updateRule(rule, true, listAll);

            // Request permissions
            if (isChecked && !Util.hasPhoneStatePermission(context))
                context.requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE },
                        MainActivity.REQUEST_ROAMING);
        }
    });

    // Reset rule
    holder.btnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_clear_rules, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    holder.cbApply.setChecked(true);
                    holder.cbWifi.setChecked(rule.wifi_default);
                    holder.cbOther.setChecked(rule.other_default);
                    holder.cbScreenWifi.setChecked(rule.screen_wifi_default);
                    holder.cbScreenOther.setChecked(rule.screen_other_default);
                    holder.cbRoaming.setChecked(rule.roaming_default);
                }
            });
        }
    });

    // Live
    holder.ivLive.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            live = !live;
            TypedValue tv = new TypedValue();
            view.getContext().getTheme().resolveAttribute(live ? R.attr.iconPause : R.attr.iconPlay, tv, true);
            holder.ivLive.setImageResource(tv.resourceId);
            if (live)
                AdapterRule.this.notifyDataSetChanged();
        }
    });

    // Show logging is disabled
    boolean log_app = prefs.getBoolean("log_app", false);
    holder.tvNoLog.setVisibility(log_app ? View.GONE : View.VISIBLE);
    holder.tvNoLog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show filtering is disabled
    boolean filter = prefs.getBoolean("filter", false);
    holder.tvNoFilter.setVisibility(filter ? View.GONE : View.VISIBLE);
    holder.tvNoFilter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show access rules
    if (rule.expanded) {
        // Access the database when expanded only
        final AdapterAccess badapter = new AdapterAccess(context,
                DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid));
        holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int bposition, long bid) {
                PackageManager pm = context.getPackageManager();
                Cursor cursor = (Cursor) badapter.getItem(bposition);
                final long id = cursor.getLong(cursor.getColumnIndex("ID"));
                final int version = cursor.getInt(cursor.getColumnIndex("version"));
                final int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
                final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
                final int dport = cursor.getInt(cursor.getColumnIndex("dport"));
                long time = cursor.getLong(cursor.getColumnIndex("time"));
                int block = cursor.getInt(cursor.getColumnIndex("block"));

                PopupMenu popup = new PopupMenu(context, context.findViewById(R.id.vwPopupAnchor));
                popup.inflate(R.menu.access);

                popup.getMenu().findItem(R.id.menu_host).setTitle(Util.getProtocolName(protocol, version, false)
                        + " " + daddr + (dport > 0 ? "/" + dport : ""));

                //                    markPro(popup.getMenu().findItem(R.id.menu_allow), ActivityPro.SKU_FILTER);
                //                    markPro(popup.getMenu().findItem(R.id.menu_block), ActivityPro.SKU_FILTER);

                // Whois
                final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.tcpiputils.com/whois-lookup/" + daddr));
                if (pm.resolveActivity(lookupIP, 0) == null)
                    popup.getMenu().removeItem(R.id.menu_whois);
                else
                    popup.getMenu().findItem(R.id.menu_whois)
                            .setTitle(context.getString(R.string.title_log_whois, daddr));

                // Lookup port
                final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.speedguide.net/port.php?port=" + dport));
                if (dport <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                    popup.getMenu().removeItem(R.id.menu_port);
                else
                    popup.getMenu().findItem(R.id.menu_port)
                            .setTitle(context.getString(R.string.title_log_port, dport));

                popup.getMenu().findItem(R.id.menu_time)
                        .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                        case R.id.menu_whois:
                            context.startActivity(lookupIP);
                            return true;

                        case R.id.menu_port:
                            context.startActivity(lookupPort);
                            return true;

                        case R.id.menu_allow:
                            if (true) {
                                DatabaseHelper.getInstance(context).setAccess(id, 0);
                                ServiceSinkhole.reload("allow host", context);
                            }
                            //                                        context.startActivity(new Intent(context, ActivityPro.class));
                            return true;

                        case R.id.menu_block:
                            if (true) {
                                DatabaseHelper.getInstance(context).setAccess(id, 1);
                                ServiceSinkhole.reload("block host", context);
                            }
                            //                                        context.startActivity(new Intent(context, ActivityPro.class));
                            return true;

                        case R.id.menu_reset:
                            DatabaseHelper.getInstance(context).setAccess(id, -1);
                            ServiceSinkhole.reload("reset host", context);
                            return true;
                        }
                        return false;
                    }
                });

                if (block == 0)
                    popup.getMenu().removeItem(R.id.menu_allow);
                else if (block == 1)
                    popup.getMenu().removeItem(R.id.menu_block);

                popup.show();
            }
        });

        holder.lvAccess.setAdapter(badapter);
    } else {
        holder.lvAccess.setAdapter(null);
        holder.lvAccess.setOnItemClickListener(null);
    }

    // Clear access log
    holder.btnClearAccess.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid, true);
                    if (!live)
                        notifyDataSetChanged();
                    if (rv != null)
                        rv.scrollToPosition(position);
                }
            });
        }
    });

    // Notify on access
    holder.cbNotify.setEnabled(prefs.getBoolean("notify_access", false) && rule.apply);
    holder.cbNotify.setOnCheckedChangeListener(null);
    holder.cbNotify.setChecked(rule.notify);
    holder.cbNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.notify = isChecked;
            updateRule(rule, true, listAll);
        }
    });
}

From source file:eu.faircode.netguard.AdapterRule.java

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    // Get rule/*from w w  w.  ja  v  a2  s  .c  o  m*/
    final Rule rule = listFiltered.get(position);

    // Handle expanding/collapsing
    holder.llApplication.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rule.expanded = !rule.expanded;
            notifyItemChanged(position);
        }
    });

    // Show if non default rules
    holder.itemView.setBackgroundColor(rule.changed ? colorChanged : Color.TRANSPARENT);

    // Show expand/collapse indicator
    holder.ivExpander.setImageLevel(rule.expanded ? 1 : 0);

    // Show application icon
    if (rule.info.applicationInfo == null || rule.info.applicationInfo.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(holder.ivIcon);
    else {
        Uri uri = Uri
                .parse("android.resource://" + rule.info.packageName + "/" + rule.info.applicationInfo.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(holder.ivIcon);
    }

    // Show application label
    holder.tvName.setText(rule.name);

    // Show application state
    int color = rule.system ? colorOff : colorText;
    if (!rule.internet || !rule.enabled)
        color = Color.argb(128, Color.red(color), Color.green(color), Color.blue(color));
    holder.tvName.setTextColor(color);

    // Show rule count
    new AsyncTask<Object, Object, Long>() {
        @Override
        protected void onPreExecute() {
            holder.tvHosts.setVisibility(View.GONE);
        }

        @Override
        protected Long doInBackground(Object... objects) {
            return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid);
        }

        @Override
        protected void onPostExecute(Long rules) {
            if (rules > 0) {
                holder.tvHosts.setVisibility(View.VISIBLE);
                holder.tvHosts.setText(Long.toString(rules));
            }
        }
    }.execute();

    // Wi-Fi settings
    holder.cbWifi.setEnabled(rule.apply);
    holder.cbWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.cbWifi.setOnCheckedChangeListener(null);
    holder.cbWifi.setChecked(rule.wifi_blocked);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbWifi));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.wifi_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.wifi_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenWifi.setEnabled(rule.apply);
    holder.ivScreenWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.ivScreenWifi.setVisibility(rule.screen_wifi && rule.wifi_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenWifi.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    // Mobile settings
    holder.cbOther.setEnabled(rule.apply);
    holder.cbOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.cbOther.setOnCheckedChangeListener(null);
    holder.cbOther.setChecked(rule.other_blocked);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbOther));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.other_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.other_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenOther.setEnabled(rule.apply);
    holder.ivScreenOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.ivScreenOther.setVisibility(rule.screen_other && rule.other_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenOther.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    holder.tvRoaming.setTextColor(rule.apply ? colorOff : colorGrayed);
    holder.tvRoaming.setAlpha(otherActive ? 1 : 0.5f);
    holder.tvRoaming.setVisibility(
            rule.roaming && (!rule.other_blocked || rule.screen_other) ? View.VISIBLE : View.INVISIBLE);

    // Expanded configuration section
    holder.llConfiguration.setVisibility(rule.expanded ? View.VISIBLE : View.GONE);

    // Show application details
    holder.tvUid
            .setText(rule.info.applicationInfo == null ? "?" : Integer.toString(rule.info.applicationInfo.uid));
    holder.tvPackage.setText(rule.info.packageName);
    holder.tvVersion.setText(rule.info.versionName + '/' + rule.info.versionCode);
    holder.tvDescription.setVisibility(rule.description == null ? View.GONE : View.VISIBLE);
    holder.tvDescription.setText(rule.description);

    // Show application state
    holder.tvInternet.setVisibility(rule.internet ? View.GONE : View.VISIBLE);
    holder.tvDisabled.setVisibility(rule.enabled ? View.GONE : View.VISIBLE);

    // Show traffic statistics
    holder.tvStatistics.setText(context.getString(R.string.msg_mbday, rule.upspeed, rule.downspeed));

    // Apply
    holder.cbApply.setEnabled(rule.pkg);
    holder.cbApply.setOnCheckedChangeListener(null);
    holder.cbApply.setChecked(rule.apply);
    holder.cbApply.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.apply = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show related
    holder.btnRelated.setVisibility(rule.relateduids ? View.VISIBLE : View.GONE);
    holder.btnRelated.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent main = new Intent(context, ActivityMain.class);
            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(rule.info.applicationInfo.uid));
            context.startActivity(main);
        }
    });

    // Fetch settings
    holder.ibFetch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new AsyncTask<Object, Object, Object>() {
                @Override
                protected void onPreExecute() {
                    holder.ibFetch.setEnabled(false);
                }

                @Override
                protected Object doInBackground(Object... args) {
                    HttpsURLConnection urlConnection = null;
                    try {
                        JSONObject json = new JSONObject();

                        json.put("type", "fetch");
                        json.put("country", Locale.getDefault().getCountry());
                        json.put("netguard", Util.getSelfVersionCode(context));
                        json.put("fingerprint", Util.getFingerprint(context));

                        JSONObject pkg = new JSONObject();
                        pkg.put("name", rule.info.packageName);
                        pkg.put("version_code", rule.info.versionCode);
                        pkg.put("version_name", rule.info.versionName);

                        JSONArray pkgs = new JSONArray();
                        pkgs.put(pkg);
                        json.put("package", pkgs);

                        urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection();
                        urlConnection.setConnectTimeout(cTimeOutMs);
                        urlConnection.setReadTimeout(cTimeOutMs);
                        urlConnection.setRequestProperty("Accept", "application/json");
                        urlConnection.setRequestProperty("Content-type", "application/json");
                        urlConnection.setRequestMethod("POST");
                        urlConnection.setDoInput(true);
                        urlConnection.setDoOutput(true);

                        Log.i(TAG, "Request=" + json.toString());
                        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                        out.write(json.toString().getBytes()); // UTF-8
                        out.flush();

                        int code = urlConnection.getResponseCode();
                        if (code != HttpsURLConnection.HTTP_OK)
                            throw new IOException("HTTP " + code);

                        InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
                        String response = Util.readString(isr).toString();
                        Log.i(TAG, "Response=" + response);
                        JSONObject jfetched = new JSONObject(response);
                        JSONArray jpkgs = jfetched.getJSONArray("package");
                        for (int i = 0; i < jpkgs.length(); i++) {
                            JSONObject jpkg = jpkgs.getJSONObject(i);
                            String name = jpkg.getString("name");
                            int wifi = jpkg.getInt("wifi");
                            int wifi_screen = jpkg.getInt("wifi_screen");
                            int other = jpkg.getInt("other");
                            int other_screen = jpkg.getInt("other_screen");
                            int roaming = jpkg.getInt("roaming");
                            int devices = jpkg.getInt("devices");

                            double conf_wifi;
                            boolean block_wifi;
                            if (rule.wifi_default) {
                                conf_wifi = confidence(devices - wifi, devices);
                                block_wifi = !(devices - wifi > wifi && conf_wifi > cConfidence);
                            } else {
                                conf_wifi = confidence(wifi, devices);
                                block_wifi = (wifi > devices - wifi && conf_wifi > cConfidence);
                            }

                            boolean allow_wifi_screen = rule.screen_wifi_default;
                            if (block_wifi)
                                allow_wifi_screen = (wifi_screen > wifi / 2);

                            double conf_other;
                            boolean block_other;
                            if (rule.other_default) {
                                conf_other = confidence(devices - other, devices);
                                block_other = !(devices - other > other && conf_other > cConfidence);
                            } else {
                                conf_other = confidence(other, devices);
                                block_other = (other > devices - other && conf_other > cConfidence);
                            }

                            boolean allow_other_screen = rule.screen_other_default;
                            if (block_other)
                                allow_other_screen = (other_screen > other / 2);

                            boolean block_roaming = rule.roaming_default;
                            if (!block_other || allow_other_screen)
                                block_roaming = (roaming > (devices - other) / 2);

                            Log.i(TAG,
                                    "pkg=" + name + " wifi=" + wifi + "/" + wifi_screen + "=" + block_wifi + "/"
                                            + allow_wifi_screen + " " + Math.round(100 * conf_wifi) + "%"
                                            + " other=" + other + "/" + other_screen + "/" + roaming + "="
                                            + block_other + "/" + allow_other_screen + "/" + block_roaming + " "
                                            + Math.round(100 * conf_other) + "%" + " devices=" + devices);

                            rule.wifi_blocked = block_wifi;
                            rule.screen_wifi = allow_wifi_screen;
                            rule.other_blocked = block_other;
                            rule.screen_other = allow_other_screen;
                            rule.roaming = block_roaming;
                        }

                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        return ex;

                    } finally {
                        if (urlConnection != null)
                            urlConnection.disconnect();
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(Object result) {
                    holder.ibFetch.setEnabled(true);
                    updateRule(rule, true, listAll);
                }

            }.execute(rule);
        }
    });

    // Launch application settings
    final Intent settings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    settings.setData(Uri.parse("package:" + rule.info.packageName));
    holder.ibSettings.setVisibility(
            settings.resolveActivity(context.getPackageManager()) == null ? View.GONE : View.VISIBLE);
    holder.ibSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(settings);
        }
    });

    // Launch application
    holder.ibLaunch.setVisibility(rule.intent == null ? View.GONE : View.VISIBLE);
    holder.ibLaunch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(rule.intent);
        }
    });

    // Show Wi-Fi screen on condition
    holder.cbScreenWifi.setEnabled(rule.wifi_blocked && rule.apply);
    holder.cbScreenWifi.setOnCheckedChangeListener(null);
    holder.cbScreenWifi.setChecked(rule.screen_wifi);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivWifiLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    holder.cbScreenWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_wifi = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    // Show mobile screen on condition
    holder.cbScreenOther.setEnabled(rule.other_blocked && rule.apply);
    holder.cbScreenOther.setOnCheckedChangeListener(null);
    holder.cbScreenOther.setChecked(rule.screen_other);
    holder.cbScreenOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_other = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show roaming condition
    holder.cbRoaming.setEnabled((!rule.other_blocked || rule.screen_other) && rule.apply);
    holder.cbRoaming.setOnCheckedChangeListener(null);
    holder.cbRoaming.setChecked(rule.roaming);
    holder.cbRoaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.roaming = isChecked;
            updateRule(rule, true, listAll);

            // Request permissions
            if (isChecked && !Util.hasPhoneStatePermission(context))
                context.requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE },
                        ActivityMain.REQUEST_ROAMING);
        }
    });

    // Reset rule
    holder.btnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_clear_rules, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    holder.cbApply.setChecked(true);
                    holder.cbWifi.setChecked(rule.wifi_default);
                    holder.cbOther.setChecked(rule.other_default);
                    holder.cbScreenWifi.setChecked(rule.screen_wifi_default);
                    holder.cbScreenOther.setChecked(rule.screen_other_default);
                    holder.cbRoaming.setChecked(rule.roaming_default);
                }
            });
        }
    });

    // Show logging is disabled
    boolean log_app = prefs.getBoolean("log_app", false);
    holder.tvNoLog.setVisibility(log_app ? View.GONE : View.VISIBLE);
    holder.tvNoLog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show filtering is disabled
    boolean filter = prefs.getBoolean("filter", false);
    holder.tvNoFilter.setVisibility(filter ? View.GONE : View.VISIBLE);
    holder.tvNoFilter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show access rules
    if (rule.expanded) {
        // Access the database when expanded only
        final AdapterAccess badapter = new AdapterAccess(context,
                DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid));
        holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int bposition, long bid) {
                PackageManager pm = context.getPackageManager();
                Cursor cursor = (Cursor) badapter.getItem(bposition);
                final long id = cursor.getLong(cursor.getColumnIndex("ID"));
                final int version = cursor.getInt(cursor.getColumnIndex("version"));
                final int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
                final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
                final int dport = cursor.getInt(cursor.getColumnIndex("dport"));
                long time = cursor.getLong(cursor.getColumnIndex("time"));
                int block = cursor.getInt(cursor.getColumnIndex("block"));

                PopupMenu popup = new PopupMenu(context, context.findViewById(R.id.vwPopupAnchor));
                popup.inflate(R.menu.access);

                popup.getMenu().findItem(R.id.menu_host).setTitle(Util.getProtocolName(protocol, version, false)
                        + " " + daddr + (dport > 0 ? "/" + dport : ""));

                // Whois
                final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.tcpiputils.com/whois-lookup/" + daddr));
                if (pm.resolveActivity(lookupIP, 0) == null)
                    popup.getMenu().removeItem(R.id.menu_whois);
                else
                    popup.getMenu().findItem(R.id.menu_whois)
                            .setTitle(context.getString(R.string.title_log_whois, daddr));

                // Lookup port
                final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.speedguide.net/port.php?port=" + dport));
                if (dport <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                    popup.getMenu().removeItem(R.id.menu_port);
                else
                    popup.getMenu().findItem(R.id.menu_port)
                            .setTitle(context.getString(R.string.title_log_port, dport));

                popup.getMenu().findItem(R.id.menu_time)
                        .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                        case R.id.menu_whois:
                            context.startActivity(lookupIP);
                            return true;

                        case R.id.menu_port:
                            context.startActivity(lookupPort);
                            return true;

                        case R.id.menu_allow:
                            if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) {
                                DatabaseHelper.getInstance(context).setAccess(id, 0);
                                ServiceSinkhole.reload("allow host", context);
                                if (rule.submit)
                                    ServiceJob.submit(rule, version, protocol, daddr, dport, 0, context);
                            } else
                                context.startActivity(new Intent(context, ActivityPro.class));
                            return true;

                        case R.id.menu_block:
                            if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) {
                                DatabaseHelper.getInstance(context).setAccess(id, 1);
                                ServiceSinkhole.reload("block host", context);
                                if (rule.submit)
                                    ServiceJob.submit(rule, version, protocol, daddr, dport, 1, context);
                            } else
                                context.startActivity(new Intent(context, ActivityPro.class));
                            return true;

                        case R.id.menu_reset:
                            DatabaseHelper.getInstance(context).setAccess(id, -1);
                            ServiceSinkhole.reload("reset host", context);
                            if (rule.submit)
                                ServiceJob.submit(rule, version, protocol, daddr, dport, -1, context);
                            return true;
                        }
                        return false;
                    }
                });

                if (block == 0)
                    popup.getMenu().removeItem(R.id.menu_allow);
                else if (block == 1)
                    popup.getMenu().removeItem(R.id.menu_block);

                popup.show();
            }
        });

        holder.lvAccess.setAdapter(badapter);
    } else {
        holder.lvAccess.setAdapter(null);
        holder.lvAccess.setOnItemClickListener(null);
    }

    // Clear access log
    holder.btnClearAccess.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid, true);
                    if (rv != null)
                        rv.scrollToPosition(position);
                }
            });
        }
    });

    // Notify on access
    holder.cbNotify.setEnabled(prefs.getBoolean("notify_access", false) && rule.apply);
    holder.cbNotify.setOnCheckedChangeListener(null);
    holder.cbNotify.setChecked(rule.notify);
    holder.cbNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.notify = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Usage data sharing
    holder.cbSubmit
            .setVisibility(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? View.VISIBLE : View.GONE);
    holder.cbSubmit.setOnCheckedChangeListener(null);
    holder.cbSubmit.setChecked(rule.submit);
    holder.cbSubmit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.submit = isChecked;
            updateRule(rule, true, listAll);
        }
    });
}

From source file:com.master.metehan.filtereagle.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);//from w  w  w .j a  v a 2 s.  co  m
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    SwitchCompat swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    boolean log = prefs.getBoolean("log", false);

    // Show disabled message
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);

    // Set enabled switch
    swEnabled.setChecked(log);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            prefs.edit().putBoolean("log", isChecked).apply();
        }
    });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = (ListView) findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, port));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                            ServiceSinkhole.reload("allow host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    case R.id.menu_block:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                            ServiceSinkhole.reload("block host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}

From source file:eu.faircode.adblocker.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);//  www . ja  v  a 2s .c  om
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    SwitchCompat swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    boolean log = prefs.getBoolean("log", false);

    // Show disabled message
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);

    // Set enabled switch
    swEnabled.setChecked(log);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            prefs.edit().putBoolean("log", isChecked).apply();
        }
    });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = (ListView) findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, dport));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                            ServiceSinkhole.reload("allow host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    case R.id.menu_block:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                            ServiceSinkhole.reload("block host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}

From source file:android_network.hetnet.vpn_service.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);//w w w  . j  a  v a2  s  . co m
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    SwitchCompat swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    boolean log = prefs.getBoolean("log", false);

    // Show disabled message
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);

    // Set enabled switch
    swEnabled.setChecked(log);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            prefs.edit().putBoolean("log", isChecked).apply();
        }
    });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = (ListView) findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    // -- the adapter holds rows of data entries -> AdapterLog class
    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    // -- when clicking the log items
    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, port));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, MainActivity.class);
                        main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        if (true) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                            ServiceSinkhole.reload("allow host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, MainActivity.class);
                            main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        }

                        return true;

                    case R.id.menu_block:
                        if (true) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                            ServiceSinkhole.reload("block host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, MainActivity.class);
                            main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        }
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}

From source file:eu.faircode.netguard.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);/*  ww  w  .  j  av  a  2  s  . co  m*/
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    SwitchCompat swEnabled = actionView.findViewById(R.id.swEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    boolean log = prefs.getBoolean("log", false);

    // Show disabled message
    TextView tvDisabled = findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);

    // Set enabled switch
    swEnabled.setChecked(log);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            prefs.edit().putBoolean("log", isChecked).apply();
        }
    });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, port));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                            ServiceSinkhole.reload("allow host", ActivityLog.this, false);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    case R.id.menu_block:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                            ServiceSinkhole.reload("block host", ActivityLog.this, false);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}

From source file:com.zhengde163.netguard.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    //        Util.setTheme(this);
    setTheme(R.style.AppThemeBlue);/* w w  w  .jav  a 2 s.  co  m*/
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    //        SwitchCompat swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);
    ImageView ivEnabled = (ImageView) actionView.findViewById(R.id.ivEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    log = prefs.getBoolean("log", false);

    // Show disabled message
    //        TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    //        tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);
    final LinearLayout ly = (LinearLayout) findViewById(R.id.lldisable);
    ly.setVisibility(log ? View.GONE : View.VISIBLE);

    ImageView ivClose = (ImageView) findViewById(R.id.ivClose);
    ivClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ly.setVisibility(View.GONE);
        }
    });
    // Set enabled switch
    //        swEnabled.setChecked(log);
    if (ivEnabled != null) {
        if (log) {
            ivEnabled.setImageResource(R.drawable.on);
        } else {
            ivEnabled.setImageResource(R.drawable.off);
        }
        ivEnabled.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                log = !log;
                boolean isChecked = log;
                prefs.edit().putBoolean("log", isChecked).apply();

            }
        });
    }
    //        swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    //            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    //                prefs.edit().putBoolean("log", isChecked).apply();
    //            }
    //        });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = (ListView) findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, port));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                        ServiceSinkhole.reload("allow host", ActivityLog.this);
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;

                    case R.id.menu_block:
                        DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                        ServiceSinkhole.reload("block host", ActivityLog.this);
                        Intent main1 = new Intent(ActivityLog.this, ActivityMain.class);
                        main1.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main1);
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}