Search in sources :

Example 91 with PopupMenu

use of android.widget.PopupMenu in project WordPress-Android by wordpress-mobile.

the class FollowHelper method showPopup.

public void showPopup(View anchor, final FollowDataModel followData) {
    if (mActivityRef.get() == null || mActivityRef.get().isFinishing()) {
        return;
    }
    final String workingText = followData.getFollowingText();
    final String followText = followData.getFollowText();
    final String unfollowText = followData.getFollowingHoverText();
    final PopupMenu popup = new PopupMenu(mActivityRef.get(), anchor);
    final MenuItem menuItem;
    if (followData.isRestCallInProgress) {
        menuItem = popup.getMenu().add(workingText);
    } else {
        menuItem = popup.getMenu().add(followData.isFollowing() ? unfollowText : followText);
    }
    menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            item.setTitle(workingText);
            item.setOnMenuItemClickListener(null);
            final RestClientUtils restClientUtils = WordPress.getRestClientUtils();
            final String restPath;
            if (!followData.isFollowing()) {
                restPath = String.format(Locale.US, "/sites/%s/follows/new", followData.getSiteID());
            } else {
                restPath = String.format(Locale.US, "/sites/%s/follows/mine/delete", followData.getSiteID());
            }
            followData.isRestCallInProgress = true;
            FollowRestListener vListener = new FollowRestListener(mActivityRef.get(), followData);
            restClientUtils.post(restPath, vListener, vListener);
            AppLog.d(AppLog.T.STATS, "Enqueuing the following REST request " + restPath);
            return true;
        }
    });
    popup.show();
}
Also used : RestClientUtils(org.wordpress.android.networking.RestClientUtils) MenuItem(android.view.MenuItem) PopupMenu(android.widget.PopupMenu)

Example 92 with PopupMenu

use of android.widget.PopupMenu in project NetGuard by M66B.

the class AdapterRule method onBindViewHolder.

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    // Get rule
    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);
    holder.tvHosts.setVisibility(rule.hosts > 0 ? View.VISIBLE : View.GONE);
    holder.tvHosts.setText(Long.toString(rule.hosts));
    // Lockdown settings
    boolean lockdown = prefs.getBoolean("lockdown", false);
    boolean lockdown_wifi = prefs.getBoolean("lockdown_wifi", true);
    boolean lockdown_other = prefs.getBoolean("lockdown_other", true);
    if ((otherActive && !lockdown_other) || (wifiActive && !lockdown_wifi))
        lockdown = false;
    holder.rlLockdown.setVisibility(lockdown && !rule.lockdown ? View.VISIBLE : View.GONE);
    holder.ivLockdown.setEnabled(rule.apply);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivLockdown.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOff : colorGrayed);
    }
    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 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
    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);
        }
    });
    // 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);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }
    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);
        }
    });
    // Show lockdown
    holder.cbLockdown.setEnabled(rule.apply);
    holder.cbLockdown.setOnCheckedChangeListener(null);
    holder.cbLockdown.setChecked(rule.lockdown);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivLockdownLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }
    holder.cbLockdown.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.lockdown = isChecked;
            updateRule(rule, true, listAll);
        }
    });
    // 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);
                    holder.cbLockdown.setChecked(false);
                }
            });
        }
    });
    holder.llFilter.setVisibility(Util.canFilter(context) ? View.VISIBLE : View.GONE);
    // 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/filtering is disabled
    final boolean log_app = prefs.getBoolean("log_app", false);
    final boolean filter = prefs.getBoolean("filter", false);
    holder.tvLogging.setText(log_app && filter ? R.string.title_logging_enabled : R.string.title_logging_disabled);
    holder.btnLogging.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            LayoutInflater inflater = LayoutInflater.from(context);
            View view = inflater.inflate(R.layout.enable, null, false);
            final CheckBox cbLogging = (CheckBox) view.findViewById(R.id.cbLogging);
            final CheckBox cbFiltering = (CheckBox) view.findViewById(R.id.cbFiltering);
            TextView tvFilter4 = (TextView) view.findViewById(R.id.tvFilter4);
            cbLogging.setChecked(log_app);
            cbFiltering.setChecked(filter);
            cbFiltering.setEnabled(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
            tvFilter4.setVisibility(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? View.GONE : View.VISIBLE);
            cbLogging.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                    prefs.edit().putBoolean("log_app", checked).apply();
                    AdapterRule.this.notifyDataSetChanged();
                }
            });
            cbFiltering.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                    if (checked)
                        cbLogging.setChecked(true);
                    prefs.edit().putBoolean("filter", checked).apply();
                    ServiceSinkhole.reload("changed filter", context);
                    AdapterRule.this.notifyDataSetChanged();
                }
            });
            AlertDialog dialog = new AlertDialog.Builder(context).setView(view).setCancelable(true).create();
            dialog.show();
        }
    });
    // 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 : ""));
                SubMenu sub = popup.getMenu().findItem(R.id.menu_host).getSubMenu();
                boolean multiple = false;
                Cursor alt = null;
                try {
                    alt = DatabaseHelper.getInstance(context).getAlternateQNames(daddr);
                    while (alt.moveToNext()) {
                        multiple = true;
                        sub.add(Menu.NONE, Menu.NONE, 0, alt.getString(0)).setEnabled(false);
                    }
                } finally {
                    if (alt != null)
                        alt.close();
                }
                popup.getMenu().findItem(R.id.menu_host).setEnabled(multiple);
                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) {
                        int menu = menuItem.getItemId();
                        boolean result = false;
                        switch(menu) {
                            case R.id.menu_whois:
                                context.startActivity(lookupIP);
                                result = true;
                                break;
                            case R.id.menu_port:
                                context.startActivity(lookupPort);
                                result = true;
                                break;
                            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));
                                result = true;
                                break;
                            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));
                                result = true;
                                break;
                            case R.id.menu_reset:
                                DatabaseHelper.getInstance(context).setAccess(id, -1);
                                ServiceSinkhole.reload("reset host", context);
                                result = true;
                                break;
                        }
                        if (menu == R.id.menu_allow || menu == R.id.menu_block || menu == R.id.menu_reset)
                            new AsyncTask<Object, Object, Long>() {

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

                                @Override
                                protected void onPostExecute(Long hosts) {
                                    rule.hosts = hosts;
                                    notifyDataSetChanged();
                                }
                            }.execute();
                        return result;
                    }
                });
                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);
        }
    });
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) SpannableStringBuilder(android.text.SpannableStringBuilder) SubMenu(android.view.SubMenu) Cursor(android.database.Cursor) Uri(android.net.Uri) PackageManager(android.content.pm.PackageManager) TextView(android.widget.TextView) TypedValue(android.util.TypedValue) SharedPreferences(android.content.SharedPreferences) Drawable(android.graphics.drawable.Drawable) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) MenuItem(android.view.MenuItem) ImageView(android.widget.ImageView) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) ListView(android.widget.ListView) RecyclerView(android.support.v7.widget.RecyclerView) CheckBox(android.widget.CheckBox) LayoutInflater(android.view.LayoutInflater) AdapterView(android.widget.AdapterView) TargetApi(android.annotation.TargetApi) CompoundButton(android.widget.CompoundButton) PopupMenu(android.widget.PopupMenu)

Example 93 with PopupMenu

use of android.widget.PopupMenu in project NetGuard by M66B.

the class ActivityLog method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    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);
    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;
}
Also used : Cursor(android.database.Cursor) FilterQueryProvider(android.widget.FilterQueryProvider) PackageManager(android.content.pm.PackageManager) TextView(android.widget.TextView) UnknownHostException(java.net.UnknownHostException) SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) MenuItem(android.view.MenuItem) SearchView(android.support.v7.widget.SearchView) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) ListView(android.widget.ListView) AdapterView(android.widget.AdapterView) InetAddress(java.net.InetAddress) CompoundButton(android.widget.CompoundButton) SwitchCompat(android.support.v7.widget.SwitchCompat) PopupMenu(android.widget.PopupMenu)

Example 94 with PopupMenu

use of android.widget.PopupMenu in project NPSmiles by bmcglynn1.

the class NewsFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View viewer = inflater.inflate(R.layout.activity_news_feed, container, false);
    View popupLayout = inflater.inflate(R.layout.popup_layout_logged_in, null);
    final ListView list = (ListView) viewer.findViewById(R.id.list);
    final ArrayList<NewsMessage> newsList = new ArrayList<>();
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("Reference");
    mAuth = FirebaseAuth.getInstance();
    if (mAuth.getCurrentUser() != null) {
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PopupMenu popup = new PopupMenu(parent.getContext(), view);
                popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
                final TextView title = (TextView) view.findViewById(R.id.title);
                final TextView message = (TextView) view.findViewById(R.id.information);
                if (mAuth.getCurrentUser() != null) {
                    popup.show();
                    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            switch(item.getItemId()) {
                                case R.id.EditMenu:
                                    // refresh view if needed
                                    break;
                                case R.id.DeleteMenu:
                                    // delete from firebase
                                    // refresh view
                                    FirebaseDatabase database = FirebaseDatabase.getInstance();
                                    DatabaseReference myRef = database.getReference("Reference");
                                    Query titleQuery = myRef.child(title.getText().toString());
                                    titleQuery.addListenerForSingleValueEvent(new ValueEventListener() {

                                        @Override
                                        public void onDataChange(DataSnapshot dataSnapshot) {
                                            for (DataSnapshot titleSnapshot : dataSnapshot.getChildren()) {
                                                dataSnapshot.getRef().removeValue();
                                            }
                                        }

                                        @Override
                                        public void onCancelled(DatabaseError databaseError) {
                                        }
                                    });
                                    break;
                            }
                            return true;
                        }
                    });
                }
            }
        });
    }
    myRef.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            newsList.clear();
            for (DataSnapshot newsItem : dataSnapshot.getChildren()) {
                NewsMessage newsMessage = new NewsMessage();
                for (DataSnapshot item : newsItem.getChildren()) {
                    if (item.getKey().equals("title")) {
                        newsMessage.setTitle((String) item.getValue());
                    } else if (item.getKey().equals("message")) {
                        newsMessage.setMessage((String) item.getValue());
                    } else {
                        newsMessage.setDate((String) item.getValue());
                    }
                }
                newsList.add(newsMessage);
            }
            Collections.sort(newsList);
            CustomAdapter adapter = new CustomAdapter(context, newsList);
            list.setAdapter(adapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    return viewer;
}
Also used : FirebaseDatabase(com.google.firebase.database.FirebaseDatabase) Query(com.google.firebase.database.Query) DatabaseReference(com.google.firebase.database.DatabaseReference) ArrayList(java.util.ArrayList) MenuItem(android.view.MenuItem) DataSnapshot(com.google.firebase.database.DataSnapshot) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) ListView(android.widget.ListView) ListView(android.widget.ListView) DatabaseError(com.google.firebase.database.DatabaseError) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) ValueEventListener(com.google.firebase.database.ValueEventListener) PopupMenu(android.widget.PopupMenu)

Example 95 with PopupMenu

use of android.widget.PopupMenu in project bitcoin-wallet by bitcoin-wallet.

the class BlockListFragment method onBlockMenuClick.

@Override
public void onBlockMenuClick(final View view, final StoredBlock block) {
    final PopupMenu popupMenu = new PopupMenu(activity, view);
    popupMenu.inflate(R.menu.blocks_context);
    popupMenu.getMenu().findItem(R.id.blocks_context_browse).setVisible(Constants.ENABLE_BROWSE);
    popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(final MenuItem item) {
            switch(item.getItemId()) {
                case R.id.blocks_context_browse:
                    final String blockHash = block.getHeader().getHashAsString();
                    final Uri blockExplorerUri = config.getBlockExplorer();
                    log.info("Viewing block {} on {}", blockHash, blockExplorerUri);
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.withAppendedPath(blockExplorerUri, "block/" + blockHash)));
                    return true;
            }
            return false;
        }
    });
    popupMenu.show();
}
Also used : OnMenuItemClickListener(android.widget.PopupMenu.OnMenuItemClickListener) MenuItem(android.view.MenuItem) Intent(android.content.Intent) Uri(android.net.Uri) PopupMenu(android.widget.PopupMenu)

Aggregations

PopupMenu (android.widget.PopupMenu)99 MenuItem (android.view.MenuItem)60 View (android.view.View)44 TextView (android.widget.TextView)41 ImageView (android.widget.ImageView)30 RecyclerView (android.support.v7.widget.RecyclerView)22 TargetApi (android.annotation.TargetApi)20 SlowTest (io.github.hidroh.materialistic.test.suite.SlowTest)19 Test (org.junit.Test)19 ShadowPopupMenu (org.robolectric.shadows.ShadowPopupMenu)19 RoboMenuItem (org.robolectric.fakes.RoboMenuItem)18 Intent (android.content.Intent)14 Context (android.content.Context)12 DialogAction (com.afollestad.materialdialogs.DialogAction)12 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)12 MenuInflater (android.view.MenuInflater)10 AdapterView (android.widget.AdapterView)10 ListView (android.widget.ListView)10 Menu (android.view.Menu)9 NonNull (android.support.annotation.NonNull)8