Example usage for android.widget PopupMenu inflate

List of usage examples for android.widget PopupMenu inflate

Introduction

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

Prototype

public void inflate(@MenuRes int menuRes) 

Source Link

Document

Inflate a menu resource into this PopupMenu.

Usage

From source file:org.starfishrespect.myconsumption.android.ui.ChartChoiceFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_chart_choice, container, false);

    // Register to the EventBus
    EventBus.getDefault().register(this);

    listViewSensor = (ListView) view.findViewById(R.id.listViewSensors);
    mLinearLayout = (LinearLayout) view.findViewById(R.id.linearLayoutDateSelectionItems);
    mTextView = (TextView) view.findViewById(R.id.textViewUsername);

    spinnerDate = (Spinner) view.findViewById(R.id.spinnerDate);
    spinnerFrequency = (Spinner) view.findViewById(R.id.spinnerFrequency);
    spinnerPrecision = (Spinner) view.findViewById(R.id.spinnerPrecision);

    seekBar = (SeekBar) view.findViewById(R.id.seekBar);
    seekBarPosition = 0;/*from  w ww . j a  v  a  2 s  .c  om*/

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        // Called when the slider moves to another value
        @Override
        public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
            seekBarPosition = progresValue;
        }

        // Called when you start moving the slider
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        // Called when it seems that you are done moving the slider
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // Tell ChartViewFragment to update the graph
            EventBus.getDefault().post(new UpdateMovingAverageEvent(seekBarPosition));
        }
    });

    listViewSensor.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            lastLongClickItem = position;
            PopupMenu popup = new PopupMenu(mActivity, view);
            popup.inflate(R.menu.menu_sensor_dropdown);
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                    case R.id.action_delete_sensor:
                        if (!MiscFunctions.isOnline(mActivity)) {
                            MiscFunctions.makeOfflineDialog(mActivity).show();
                            return false;
                        }
                        deleteSensor(lastLongClickItem);
                        break;
                    case R.id.action_edit_sensor:
                        if (!MiscFunctions.isOnline(mActivity)) {
                            MiscFunctions.makeOfflineDialog(mActivity).show();
                            return false;
                        }
                        editSensor(lastLongClickItem);
                        break;
                    }
                    return false;
                }
            });
            popup.show();
            return false;
        }
    });

    return view;
}

From source file:osm.custommaps.create.PreviewMapActivity.java

private void prepareUI() {
    saveButton = (Button) findViewById(R.id.save);
    mapModeButton = (ImageButton) findViewById(R.id.mapmode);
    transparencyBar = (SeekBar) findViewById(R.id.transparencyBar);

    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override/* w  ww  . jav  a  2 s  .com*/
        public void onClick(View v) {

            computeAndReturnTiepoints();
        }
    });

    mapModeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            PopupMenu popupMenu = new PopupMenu(getApplicationContext(), view);
            popupMenu.inflate(R.menu.menu_options);

            popupMenu.show();

            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.toString()) {
                    case "Google Satellite":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.GOOGLE_SATELLITE);
                        break;
                    case "Google Maps":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.GOOGLE_MAPS);
                        break;
                    case "Google Terrain":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.GOOGLE_TERRAIN);
                        break;
                    case "Bing Maps":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.BING_MAPS);
                        break;
                    case "Bing Earth":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.BING_EARTH);
                        break;
                    case "Bing Hybrid":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.BING_HYBRID);
                        break;
                    case "Mapquest Aerial":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.MAPQUESTAERIAL_US);
                        break;
                    case "Mapquest OSM":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.MAPQUESTOSM);
                        break;
                    case "Mapnik":
                        mapView.invalidate();
                        mapView.setMaxZoomLevel(20);
                        mapView.setMinZoomLevel(3);
                        mapView.setTileSource(WMSTileSourceFactory.MAPNIK);
                        break;

                    }
                    return false;
                }
            });
        }
    });

    transparencyBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        private void updateImageOverlay(int value) {
            imageOverlay.setTransparency(value);
            mapView.invalidate();
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            updateImageOverlay(seekBar.getProgress());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            updateImageOverlay(seekBar.getProgress());
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                updateImageOverlay(seekBar.getProgress());
            }
        }
    });
}

From source file:systems.soapbox.ombuds.client.ui.WalletTransactionsFragment.java

@Override
public void onTransactionMenuClick(final View view, final Transaction tx) {
    final boolean txSent = tx.getValue(wallet).signum() < 0;
    final Address txAddress = txSent ? WalletUtils.getToAddressOfSent(tx, wallet)
            : WalletUtils.getWalletAddressOfReceived(tx, wallet);
    final byte[] txSerialized = tx.unsafeBitcoinSerialize();
    final boolean txRotation = tx.getPurpose() == Purpose.KEY_ROTATION;

    final PopupMenu popupMenu = new PopupMenu(activity, view);
    popupMenu.inflate(R.menu.wallet_transactions_context);
    final MenuItem editAddressMenuItem = popupMenu.getMenu()
            .findItem(R.id.wallet_transactions_context_edit_address);
    if (!txRotation && txAddress != null) {
        editAddressMenuItem.setVisible(true);
        final boolean isAdd = AddressBookProvider.resolveLabel(activity, txAddress.toString()) == null;
        final boolean isOwn = wallet.isPubKeyHashMine(txAddress.getHash160());

        if (isOwn)
            editAddressMenuItem.setTitle(isAdd ? R.string.edit_address_book_entry_dialog_title_add_receive
                    : R.string.edit_address_book_entry_dialog_title_edit_receive);
        else/*from www .  j a v a2s. co m*/
            editAddressMenuItem.setTitle(isAdd ? R.string.edit_address_book_entry_dialog_title_add
                    : R.string.edit_address_book_entry_dialog_title_edit);
    } else {
        editAddressMenuItem.setVisible(false);
    }

    popupMenu.getMenu().findItem(R.id.wallet_transactions_context_show_qr)
            .setVisible(!txRotation && txSerialized.length < SHOW_QR_THRESHOLD_BYTES);
    popupMenu.getMenu().findItem(R.id.wallet_transactions_context_raise_fee)
            .setVisible(RaiseFeeDialogFragment.feeCanBeRaised(wallet, tx));
    popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(final MenuItem item) {
            switch (item.getItemId()) {
            case R.id.wallet_transactions_context_edit_address:
                handleEditAddress(tx);
                return true;

            case R.id.wallet_transactions_context_show_qr:
                handleShowQr();
                return true;

            case R.id.wallet_transactions_context_browse:
                if (!txRotation)
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.withAppendedPath(config.getBlockExplorer(), "tx/" + tx.getHashAsString())));
                else
                    startActivity(new Intent(Intent.ACTION_VIEW, KEY_ROTATION_URI));
                return true;

            case R.id.wallet_transactions_context_raise_fee:
                RaiseFeeDialogFragment.show(getFragmentManager(), tx);
                return true;
            }

            return false;
        }

        private void handleEditAddress(final Transaction tx) {
            EditAddressBookEntryFragment.edit(getFragmentManager(), txAddress);
        }

        private void handleShowQr() {
            final int size = getResources().getDimensionPixelSize(R.dimen.bitmap_dialog_qr_size);
            final Bitmap qrCodeBitmap = Qr.bitmap(Qr.encodeCompressBinary(txSerialized), size);
            BitmapFragment.show(getFragmentManager(), qrCodeBitmap);
        }
    });
    popupMenu.show();
}

From source file:com.battlelancer.seriesguide.ui.SeasonsFragment.java

@Override
public void onPopupMenuClick(View v, final int seasonTvdbId, final int seasonNumber) {
    PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
    popupMenu.inflate(R.menu.seasons_popup_menu);
    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override/*from w  ww .  j a v a 2  s. c  o m*/
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.menu_action_seasons_watched_all: {
                onFlagSeasonWatched(seasonTvdbId, seasonNumber, true);
                fireTrackerEventContextMenu("Flag all watched");
                return true;
            }
            case R.id.menu_action_seasons_watched_none: {
                onFlagSeasonWatched(seasonTvdbId, seasonNumber, false);
                fireTrackerEventContextMenu("Flag all unwatched");
                return true;
            }
            case R.id.menu_action_seasons_collection_add: {
                onFlagSeasonCollected(seasonTvdbId, seasonNumber, true);
                fireTrackerEventContextMenu("Flag all collected");
                return true;
            }
            case R.id.menu_action_seasons_collection_remove: {
                onFlagSeasonCollected(seasonTvdbId, seasonNumber, false);
                fireTrackerEventContextMenu("Flag all uncollected");
                return true;
            }
            case R.id.menu_action_seasons_skip: {
                onFlagSeasonSkipped(seasonTvdbId, seasonNumber);
                fireTrackerEventContextMenu("Flag all skipped");
                return true;
            }
            case R.id.menu_action_seasons_manage_lists: {
                ManageListsDialogFragment.showListsDialog(seasonTvdbId, ListItemTypes.SEASON,
                        getFragmentManager());
                fireTrackerEventContextMenu("Manage lists");
                return true;
            }
            }
            return false;
        }
    });
    popupMenu.show();
}

From source file:com.scooter1556.sms.androidtv.fragment.AudioPlayerFragment.java

public void showOptionsMenu(View v) {
    PopupMenu popup = new PopupMenu(getActivity(), v);

    // This activity implements OnMenuItemClickListener
    popup.setOnMenuItemClickListener(this);
    popup.inflate(R.menu.menu_playlist_item);
    popup.show();//  www .  j  a va 2s  . co m
}

From source file:com.atlas.mars.weatherradar.MainActivity.java

@Override
public void onClick(View v) {
    final View _v = v;
    final MainActivity mainActivity = this;
    switch (v.getId()) {
    case R.id.buttonReload:

        /* MyFragment myFragment = (MyFragment)fragmetMap.get(posinion);// (MyFragment)pager.getChildAt(posinion);
        myFragment.reloadImg();*/
        mapFragments.get(posinion).reloadImg();
        //   reloadImg();
        break;//from   w ww.  j  a  v  a2 s  . c  o  m
    case R.id.buttonMenu:
        PopupMenu popupMenu = new PopupMenu(this, v);
        popupMenu.inflate(R.menu.menu_main);
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(this);
        break;
    }
}

From source file:info.papdt.blacklight.support.adapter.WeiboAdapter.java

void buildPopup(final ViewHolder h) {
    PopupMenu p = new PopupMenu(mContext, h.popup);
    p.inflate(R.menu.popup);
    final Menu m = p.getMenu();

    // Show needed items
    m.findItem(R.id.popup_copy).setVisible(true);
    if (h.msg instanceof CommentModel) {
        m.findItem(R.id.popup_reply).setVisible(true);

        CommentModel cmt = (CommentModel) h.msg;
        if (cmt.user.id.equals(mUid)
                || (cmt.status != null && cmt.status.user != null && cmt.status.user.id.equals(mUid))) {
            m.findItem(R.id.popup_delete).setVisible(true);
        }/*from w ww. j  av  a 2  s.com*/
    } else {
        m.findItem(R.id.popup_repost).setVisible(true);
        m.findItem(R.id.popup_comment).setVisible(true);

        if (h.msg.liked) {
            m.findItem(R.id.popup_unlike).setVisible(true);
        } else {
            m.findItem(R.id.popup_like).setVisible(true);
        }

        if (h.msg.user != null && h.msg.user.id.equals(mUid)) {
            m.findItem(R.id.popup_delete).setVisible(true);
        }
    }

    p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            int id = item.getItemId();
            if (id == R.id.popup_delete) {
                h.delete();
            } else if (id == R.id.popup_copy) {
                h.copy();
            } else if (id == R.id.popup_comment || id == R.id.popup_reply) {
                h.reply();
            } else if (id == R.id.popup_repost) {
                h.repost();
            } else if (id == R.id.popup_like || id == R.id.popup_unlike) {
                new LikeTask().execute(h.msg, h, m);
            }

            return true;
        }
    });

    // Pop up!
    p.show();
}

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   ww  w  . j a v a  2 s .  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, 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);//from  www .j a  v  a  2  s .  c o 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, 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.  jav a  2 s.com
    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;
}