Example usage for android.widget PopupMenu show

List of usage examples for android.widget PopupMenu show

Introduction

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

Prototype

public void show() 

Source Link

Document

Show the menu popup anchored to the view specified during construction.

Usage

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

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // Get rule//from w  w  w.j  a v  a 2 s  .  co  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);
    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) {
                    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 : ""));
                    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_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);
                    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.filemanager.free.adapters.Recycleradapter.java

void showPopup(View v, final Layoutelements rowItem) {
    v.setOnClickListener(new View.OnClickListener() {
        @Override/*from w  ww .  j  a v  a 2 s  .co  m*/
        public void onClick(View view) {
            PopupMenu popupMenu = new PopupMenu(main.getActivity(), view);
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                    case R.id.about:
                        main.utils.showProps((rowItem).generateBaseFile(), rowItem.getPermissions(), main,
                                main.ROOT_MODE);
                        return true;
                    case R.id.share:
                        ArrayList<File> arrayList = new ArrayList<File>();
                        arrayList.add(new File(rowItem.getDesc()));
                        main.utils.shareFiles(arrayList, main.MAIN_ACTIVITY, main.theme1,
                                Color.parseColor(main.fabSkin));
                        return true;
                    case R.id.rename:
                        main.rename(rowItem.generateBaseFile());
                        return true;
                    case R.id.cpy:
                        MainActivity MAIN_ACTIVITY = main.MAIN_ACTIVITY;
                        main.MAIN_ACTIVITY.MOVE_PATH = null;
                        ArrayList<BaseFile> copies = new ArrayList<>();
                        copies.add(rowItem.generateBaseFile());
                        MAIN_ACTIVITY.COPY_PATH = copies;
                        MAIN_ACTIVITY.supportInvalidateOptionsMenu();
                        return true;
                    case R.id.cut:
                        MainActivity MAIN_ACTIVITY1 = main.MAIN_ACTIVITY;
                        MAIN_ACTIVITY1.COPY_PATH = null;
                        ArrayList<BaseFile> copie = new ArrayList<>();
                        copie.add(rowItem.generateBaseFile());
                        MAIN_ACTIVITY1.MOVE_PATH = copie;
                        MAIN_ACTIVITY1.supportInvalidateOptionsMenu();
                        return true;
                    case R.id.ex:
                        main.MAIN_ACTIVITY.mainActivityHelper.extractFile(new File(rowItem.getDesc()));
                        return true;
                    case R.id.book:
                        DataUtils.addBook(new String[] { rowItem.getTitle(), rowItem.getDesc() }, true);
                        main.MAIN_ACTIVITY.updateDrawer();
                        Toast.makeText(main.getActivity(),
                                main.utils.getString(main.getActivity(), R.string.bookmarksadded),
                                Toast.LENGTH_LONG).show();
                        return true;

                    }
                    return false;
                }
            });
            popupMenu.inflate(R.menu.item_extras);
            String x = rowItem.getDesc().toLowerCase();
            if (rowItem.isDirectory())
                popupMenu.getMenu().findItem(R.id.share).setVisible(false);
            if (x.endsWith(".zip") || x.endsWith(".jar") || x.endsWith(".apk") || x.endsWith(".rar")
                    || x.endsWith(".tar") || x.endsWith(".tar.gz"))
                popupMenu.getMenu().findItem(R.id.ex).setVisible(true);
            popupMenu.show();
        }
    });

}

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;

        }/*from   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:com.audiokernel.euphonyrmt.fragments.NowPlayingFragment.java

/**
 * Run during fragment initialization, this sets up the song info popup menu.
 *
 * @param view The view in which to setup the song info View for this class.
 * @return The song info view used as a field in this class.
 *///  w  w  w.j  a v a  2  s .co m
private View getSongInfo(final View view) {
    final View songInfo = view.findViewById(R.id.songInfo);

    final PopupMenu popupMenu = new PopupMenu(mActivity, songInfo);
    final Menu menu = popupMenu.getMenu();
    menu.add(Menu.NONE, POPUP_ALBUM, Menu.NONE, R.string.goToAlbum);
    menu.add(Menu.NONE, POPUP_ARTIST, Menu.NONE, R.string.goToArtist);
    menu.add(Menu.NONE, POPUP_ALBUM_ARTIST, Menu.NONE, R.string.goToAlbumArtist);
    menu.add(Menu.NONE, POPUP_FOLDER, Menu.NONE, R.string.goToFolder);
    menu.add(Menu.NONE, POPUP_CURRENT, Menu.NONE, R.string.goToCurrent);
    menu.add(Menu.NONE, POPUP_SHARE, Menu.NONE, R.string.share);
    popupMenu.setOnMenuItemClickListener(this);
    mPopupMenuTouchListener = PopupMenuCompat.getDragToOpenListener(popupMenu);

    final PopupMenu popupMenuStream = new PopupMenu(mActivity, songInfo);
    final Menu menuStream = popupMenuStream.getMenu();
    menuStream.add(Menu.NONE, POPUP_STREAM, Menu.NONE, R.string.goToStream);
    menuStream.add(Menu.NONE, POPUP_CURRENT, Menu.NONE, R.string.goToCurrent);
    menuStream.add(Menu.NONE, POPUP_SHARE, Menu.NONE, R.string.share);
    popupMenuStream.setOnMenuItemClickListener(this);
    mPopupMenuStreamTouchListener = PopupMenuCompat.getDragToOpenListener(popupMenuStream);

    songInfo.setOnClickListener(new OnClickListener() {

        /**
         * Checks whether the album artist should be on the popup menu for the current track.
         *
         * @return True if the album artist popup menu entry should be visible, false otherwise.
         */
        private boolean isAlbumArtistVisible() {
            boolean albumArtistEnabled = false;
            final String albumArtist = mCurrentSong.getAlbumArtist();

            if (albumArtist != null && !albumArtist.isEmpty()) {
                final String artist = mCurrentSong.getArtist();

                if (isArtistVisible() && !albumArtist.equals(artist)) {
                    albumArtistEnabled = true;
                }
            }

            return albumArtistEnabled;
        }

        /**
         * Checks whether the album should be on the popup menu for the current track.
         *
         * @return True if the album popup menu entry should be visible, false otherwise.
         */
        private boolean isAlbumVisible() {
            final boolean isAlbumVisible;
            final String album = mCurrentSong.getAlbum();

            if (album != null && !album.isEmpty()) {
                isAlbumVisible = true;
            } else {
                isAlbumVisible = false;
            }

            return isAlbumVisible;
        }

        /**
         * Checks whether the artist should be on the popup menu for the current track.
         *
         * @return True if the artist popup menu entry should be visible, false otherwise.
         */
        private boolean isArtistVisible() {
            final boolean isArtistVisible;
            final String artist = mCurrentSong.getArtist();

            if (artist != null && !artist.isEmpty()) {
                isArtistVisible = true;
            } else {
                isArtistVisible = false;
            }

            return isArtistVisible;
        }

        /**
         * This method checks the dynamic entries for visibility prior to showing the song info
         * popup menu.
         *
         * @param v The view for the song info popup menu.
         */
        @Override
        public void onClick(final View v) {
            if (mCurrentSong != null) {
                if (mCurrentSong.isStream()) {
                    popupMenuStream.show();
                } else {
                    // Enable / Disable menu items that need artist and album defined.
                    menu.findItem(POPUP_ALBUM).setVisible(isAlbumVisible());
                    menu.findItem(POPUP_ARTIST).setVisible(isArtistVisible());
                    menu.findItem(POPUP_ALBUM_ARTIST).setVisible(isAlbumArtistVisible());
                    popupMenu.show();
                }
            }
        }
    });

    return songInfo;
}

From source file:org.thecongers.mcluster.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    setContentView(R.layout.activity_main);
    setTitle(R.string.app_name);/*from  w w  w. j a  va 2  s  .  c om*/

    View myView = findViewById(R.id.layoutApp);
    root = myView.getRootView();
    layoutIcons = (LinearLayout) findViewById(R.id.layoutIcons);
    layoutMiddleLeft = (LinearLayout) findViewById(R.id.layoutMiddleLeft);
    layoutMiddleRight = (LinearLayout) findViewById(R.id.layoutMiddleRight);
    layoutBottomLeft = (LinearLayout) findViewById(R.id.layoutBottomLeft);
    layoutBottomRight = (LinearLayout) findViewById(R.id.layoutBottomRight);
    imageKillSwitch = (ImageView) findViewById(R.id.imageViewKillSwitch);
    imageLeftArrow = (ImageView) findViewById(R.id.imageViewLeftArrow);
    imageRightArrow = (ImageView) findViewById(R.id.imageViewRightArrow);
    imageHighBeam = (ImageView) findViewById(R.id.imageViewHighBeam);
    imageHeatedGrips = (ImageView) findViewById(R.id.imageViewHeatedGrips);
    imageABS = (ImageView) findViewById(R.id.imageViewABS);
    imageLampf = (ImageView) findViewById(R.id.imageViewLampf);
    imageFuelWarning = (ImageView) findViewById(R.id.imageViewFuelWarning);
    imageFuelLevel = (ImageView) findViewById(R.id.imageViewFuelLevel);
    imageESA = (ImageView) findViewById(R.id.imageViewESA);
    txtSpeed = (TextView) findViewById(R.id.textViewSpeed);
    txtSpeedUnit = (TextView) findViewById(R.id.textViewSpeedUnit);
    txtGear = (TextView) findViewById(R.id.textViewGear);
    txtOdometers = (TextView) findViewById(R.id.textViewOdometer);
    txtESA = (TextView) findViewById(R.id.textViewESA);
    imageButtonTPMS = (ImageButton) findViewById(R.id.imageButtonTPMS);
    imageButtonBluetooth = (ImageButton) findViewById(R.id.imageButtonBluetooth);
    imageButtonPreference = (ImageButton) findViewById(R.id.imageButtonPreference);
    progressFuelLevel = (ProgressBar) findViewById(R.id.progressBarFuelLevel);

    // Backgrounds
    background = R.drawable.rectangle_bordered;
    backgroundDark = R.drawable.rectangle_bordered_dark;

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Update layout
    updateLayout();

    if (!sharedPrefs.getBoolean("prefEnableTPMS", false)) {
        imageButtonTPMS.setImageResource(R.mipmap.blank_icon);
        imageButtonTPMS.setEnabled(false);
    } else {
        imageButtonTPMS.setImageResource(R.mipmap.tpms_off);
        imageButtonTPMS.setEnabled(true);
    }

    // Set initial color scheme
    updateColors();
    if (sharedPrefs.getBoolean("prefNightMode", false)) {
        imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark);
    }

    // Watch for Bluetooth Changes
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(btReceiver, filter1);
    this.registerReceiver(btReceiver, filter2);
    this.registerReceiver(btReceiver, filter3);

    // Setup Text To Speech
    text2speech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                text2speech.setLanguage(Locale.US);
            }
        }
    });

    imageButtonBluetooth.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            canBusConnect();
        }
    });

    imageButtonTPMS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (sharedPrefs.getBoolean("prefEnableTPMS", false)) {
                iTPMSConnect();
            }
        }
    });

    imageButtonPreference.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(MainActivity.this, v);
            popup.getMenuInflater().inflate(R.menu.main, popup.getMenu());
            popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                    case R.id.action_settings:
                        // Settings Menu was selected
                        Intent i = new Intent(getApplicationContext(),
                                org.thecongers.mcluster.UserSettingActivity.class);
                        startActivityForResult(i, SETTINGS_RESULT);
                        return true;
                    case R.id.action_about:
                        // About was selected
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle(getResources().getString(R.string.alert_about_title));
                        builder.setMessage(readRawTextFile(MainActivity.this, R.raw.about));
                        builder.setPositiveButton(getResources().getString(R.string.alert_about_button), null);
                        builder.show();
                        return true;
                    case R.id.action_exit:
                        // Exit menu item was selected
                        if (logger != null) {
                            logger.shutdown();
                        }
                        finish();
                        System.exit(0);
                    default:
                        return true;
                    }
                }
            });

            popup.show();
        }
    });

    layoutMiddleRight.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int infoViewCurr = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0"));
            if (infoViewCurr < (numInfoViewLayouts - 1)) {
                infoViewCurr = infoViewCurr + 1;
            } else {
                infoViewCurr = 0;
            }
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putString("prefInfoView", String.valueOf(infoViewCurr));
            editor.commit();

            //update layout
            updateLayout();
        }
    });

    canBusMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Check to see if message is the correct size
                if (msg.arg1 == 27) {
                    byte[] readBuf = (byte[]) msg.obj;
                    String message = new String(readBuf);

                    //Default Units
                    String speedUnit = "km/h";
                    String odometerUnit = "km";
                    String temperatureUnit = "C";

                    String[] splitMessage = message.split(",");
                    if (splitMessage[0].contains("10C")) {

                        //RPM
                        if (sharedPrefs.getString("prefInfoView", "0").contains("0")) {
                            int rpm = (Integer.parseInt(splitMessage[4], 16) * 255
                                    + Integer.parseInt(splitMessage[3], 16)) / 4;
                            txtInfo = (TextView) findViewById(R.id.textViewInfo);
                            txtInfo.setGravity(Gravity.CENTER | Gravity.BOTTOM);
                            txtInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
                            txtInfo.setText(Integer.toString(rpm) + " RPM");
                            if (rpm > 8500) {
                                txtInfo.setTextColor(getResources().getColor(R.color.red));
                            } else {
                                txtInfo.setTextColor(getResources().getColor(android.R.color.black));
                            }
                        }

                        //Kill Switch
                        String killSwitchValue = splitMessage[5].substring(1);
                        if (killSwitchValue.contains("5") || killSwitchValue.contains("9")) {
                            //Kill Switch On
                            imageKillSwitch.setImageResource(R.mipmap.kill_switch);
                        } else {
                            //Kill Switch Off
                            imageKillSwitch.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("130")) {
                        //Turn indicators
                        String indicatorValue = splitMessage[8];

                        if (indicatorValue.contains("D7")) {
                            imageLeftArrow.setImageResource(R.mipmap.left_arrow);
                            imageRightArrow.setImageResource(R.mipmap.blank_icon);
                        } else if (indicatorValue.contains("E7")) {
                            imageLeftArrow.setImageResource(R.mipmap.blank_icon);
                            imageRightArrow.setImageResource(R.mipmap.right_arrow);
                        } else if (indicatorValue.contains("EF")) {
                            imageLeftArrow.setImageResource(R.mipmap.left_arrow);
                            imageRightArrow.setImageResource(R.mipmap.right_arrow);
                        } else {
                            imageLeftArrow.setImageResource(R.mipmap.blank_icon);
                            imageRightArrow.setImageResource(R.mipmap.blank_icon);
                        }

                        //High Beam
                        String highBeamValue = splitMessage[7].substring(1);
                        if (highBeamValue.contains("9")) {
                            //High Beam On
                            imageHighBeam.setImageResource(R.mipmap.high_beam);
                        } else {
                            //High Beam Off
                            imageHighBeam.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("294")) {
                        //Front Wheel Speed
                        double frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0
                                + Integer.parseInt(splitMessage[3], 16)) * 0.063);
                        //If 21" Wheel
                        if (sharedPrefs.getString("prefDistance", "0").contains("1")) {
                            frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0
                                    + Integer.parseInt(splitMessage[3], 16)) * 0.064);
                        }
                        if (sharedPrefs.getString("prefDistance", "0").contains("0")) {
                            speedUnit = "MPH";
                            frontSpeed = frontSpeed / 1.609344;
                        }
                        txtSpeed.setText(String.valueOf((int) Math.round(frontSpeed)));
                        txtSpeedUnit.setText(speedUnit);

                        //ABS
                        String absValue = splitMessage[2].substring(0, 1);
                        if (absValue.contains("B")) {
                            //ABS Off
                            imageABS.setImageResource(R.mipmap.abs);
                        } else {
                            //ABS On
                            imageABS.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("2BC")) {
                        //Engine Temperature
                        engineTempC = (Integer.parseInt(splitMessage[3], 16) * 0.75) - 24.0;

                        if (engineTempC >= 115.5) {
                            if (engineTempAlertTriggered == false) {
                                engineTempAlertTriggered = true;
                                speakString(getResources().getString(R.string.engine_temp_alert));
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(3));
                                editor.commit();

                                updateLayout();
                            }
                        } else {
                            engineTempAlertTriggered = false;
                        }

                        if (sharedPrefs.getString("prefInfoView", "0").contains("3")) {
                            double engineTemp = engineTempC;
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                engineTemp = (int) Math.round((9.0 / 5.0) * engineTemp + 32.0);
                                temperatureUnit = "F";
                            }
                            txtEngineTemp.setText(String.valueOf(engineTemp) + temperatureUnit);
                        }

                        // Gear
                        String gearValue = splitMessage[6].substring(0, 1);
                        String gear;
                        if (gearValue.contains("1")) {
                            gear = "1";
                        } else if (gearValue.contains("2")) {
                            gear = "N";
                        } else if (gearValue.contains("4")) {
                            gear = "2";
                        } else if (gearValue.contains("7")) {
                            gear = "3";
                        } else if (gearValue.contains("8")) {
                            gear = "4";
                        } else if (gearValue.contains("B")) {
                            gear = "5";
                        } else if (gearValue.contains("D")) {
                            gear = "6";
                        } else {
                            gear = "-";
                        }
                        txtGear.setText(gear);

                        //Air Temperature
                        airTempC = (Integer.parseInt(splitMessage[8], 16) * 0.75) - 48.0;
                        //Freeze Warning
                        if (airTempC <= 0.0) {
                            if (freezeAlertTriggered == false) {
                                freezeAlertTriggered = true;
                                speakString(getResources().getString(R.string.freeze_alert));
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(3));
                                editor.commit();

                                updateLayout();
                            }
                        } else {
                            freezeAlertTriggered = false;
                        }

                        if (sharedPrefs.getString("prefInfoView", "0").contains("3")) {
                            double airTemp = airTempC;
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                airTemp = (int) Math.round((9.0 / 5.0) * airTemp + 32.0);
                                temperatureUnit = "F";
                            }
                            txtAirTemp.setText(String.valueOf(airTemp) + temperatureUnit);
                        }

                    } else if (splitMessage[0].contains("2D0")) {
                        //Info Button
                        String infoButtonValue = splitMessage[6].substring(1);
                        if (infoButtonValue.contains("5")) {
                            //Short Press
                            if (!btnPressed) {
                                int infoButton = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0"));
                                if (infoButton < (numInfoViewLayouts - 1)) {
                                    infoButton = infoButton + 1;
                                } else {
                                    infoButton = 0;
                                }
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(infoButton));
                                editor.commit();

                                //update layout
                                updateLayout();
                                btnPressed = true;
                            }
                        } else if (infoButtonValue.contains("6")) {
                            //Long Press
                        } else {
                            btnPressed = false;
                        }

                        //Heated Grips
                        String heatedGripSwitchValue = splitMessage[8].substring(0, 1);
                        if (heatedGripSwitchValue.contains("C")) {
                            imageHeatedGrips.setImageResource(R.mipmap.blank_icon);
                        } else if (heatedGripSwitchValue.contains("D")) {
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low);
                            } else {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low_dark);
                            }
                        } else if (heatedGripSwitchValue.contains("E")) {
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high);
                            } else {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark);
                            }
                        } else {
                            imageHeatedGrips.setImageResource(R.mipmap.blank_icon);
                        }

                        //ESA Damping and Preload
                        String esaDampingValue1 = splitMessage[5].substring(1);
                        String esaDampingValue2 = splitMessage[8].substring(1);
                        String esaPreLoadValue = splitMessage[5].substring(0, 1);
                        if (esaDampingValue1.contains("B") && esaDampingValue2.contains("1")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("3")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("4")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("6")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("1")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("3")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("4")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("6")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaPreLoadValue.contains("1")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("3")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("4")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("6")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("7")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("8")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("9")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else {
                            txtESA.setText("");
                            imageESA.setImageResource(R.mipmap.blank_icon);
                        }

                        //Lamp Fault
                        //TODO: Display/speak Bulb location
                        String lampFaultValue = splitMessage[3].substring(0, 1);
                        if (lampFaultValue.contains("0")) {
                            //None
                            imageLampf.setImageResource(R.mipmap.blank_icon);
                        } else if (lampFaultValue.contains("1")) {
                            //Low Beam
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else if (lampFaultValue.contains("4")) {
                            //High Beam
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else if (lampFaultValue.contains("8")) {
                            //Signal Bulb
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else {
                            //Unknown
                            imageLampf.setImageResource(R.mipmap.lampf);
                        }

                        //Fuel Level
                        double fuelLevelPercent = ((Integer.parseInt(splitMessage[4], 16) - 73) / 182.0)
                                * 100.0;
                        progressFuelLevel.setProgress((int) Math.round(fuelLevelPercent));

                        //Fuel Level Warning
                        double fuelWarning = sharedPrefs.getInt("prefFuelWarning", 30);
                        if (fuelLevelPercent >= fuelWarning) {
                            imageFuelWarning.setImageResource(R.mipmap.blank_icon);
                            fuelAlertTriggered = false;
                            fuelReserveAlertTriggered = false;
                        } else if (fuelLevelPercent == 0) {
                            //Visual Warning
                            imageFuelWarning.setImageResource(R.mipmap.fuel_warning);
                            if (!fuelReserveAlertTriggered) {
                                fuelReserveAlertTriggered = true;
                                //Audio Warning
                                speakString(getResources().getString(R.string.fuel_alert_reserve));
                            }
                        } else {
                            //Visual Warning
                            imageFuelWarning.setImageResource(R.mipmap.fuel_warning);
                            if (!fuelAlertTriggered) {
                                fuelAlertTriggered = true;
                                //Audio Warning
                                String fuelAlert = getResources().getString(R.string.fuel_alert_begin)
                                        + String.valueOf((int) Math.round(fuelLevelPercent))
                                        + getResources().getString(R.string.fuel_alert_end);
                                speakString(fuelAlert);
                                //Suggest nearby fuel stations
                                if (!sharedPrefs.getString("prefFuelStation", "0").contains("0")) {
                                    // Display prompt to open google maps
                                    MainActivity.this.runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                                    MainActivity.this);
                                            builder.setTitle(getResources()
                                                    .getString(R.string.alert_fuel_stations_title));
                                            if (sharedPrefs.getString("prefFuelStation", "0").contains("1")) {
                                                // Search for fuel stations nearby
                                                builder.setMessage(getResources().getString(
                                                        R.string.alert_fuel_stations_message_suggestions));
                                            } else if (sharedPrefs.getString("prefFuelStation", "0")
                                                    .contains("2")) {
                                                // Route to nearest fuel station
                                                builder.setMessage(getResources().getString(
                                                        R.string.alert_fuel_stations_message_navigation));
                                            }
                                            builder.setPositiveButton(
                                                    getResources().getString(
                                                            R.string.alert_fuel_stations_button_positive),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            Uri gmmIntentUri = null;
                                                            if (sharedPrefs.getString("prefFuelStation", "0")
                                                                    .contains("1")) {
                                                                // Search for fuel stations nearby
                                                                gmmIntentUri = Uri
                                                                        .parse("geo:0,0?q=gas+station");
                                                            } else if (sharedPrefs
                                                                    .getString("prefFuelStation", "0")
                                                                    .contains("2")) {
                                                                // Route to nearest fuel station
                                                                gmmIntentUri = Uri.parse(
                                                                        "google.navigation:q=gas+station");
                                                            }
                                                            Intent mapIntent = new Intent(Intent.ACTION_VIEW,
                                                                    gmmIntentUri);
                                                            mapIntent
                                                                    .setPackage("com.google.android.apps.maps");
                                                            startActivity(mapIntent);
                                                        }
                                                    });
                                            builder.setNegativeButton(
                                                    getResources().getString(
                                                            R.string.alert_fuel_stations_button_negative),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int id) {
                                                            dialog.cancel();
                                                        }
                                                    });
                                            builder.show();
                                        }
                                    });
                                }
                            }
                        }
                    } else if (splitMessage[0].contains("3F8")) {
                        String odometerValue = "";
                        for (int i = 4; i > 1; i--) {
                            odometerValue = odometerValue + splitMessage[i];
                        }
                        double odometer = Integer.parseInt(odometerValue, 16);
                        if (sharedPrefs.getString("prefDistance", "0").contains("0")) {
                            odometerUnit = "Miles";
                            odometer = odometer * 0.6214;
                        }
                        txtOdometers.setText(String.valueOf((int) Math.round(odometer)) + " " + odometerUnit);
                    }
                    imageButtonBluetooth.setImageResource(R.mipmap.bluetooth_on);
                    if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                        // Log data
                        if (logger == null) {
                            logger = new LogData();
                        }
                        if (logger != null) {
                            logger.write(message);
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };

    sensorMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Message received
                Log.d(TAG, "iTPMS Message Received, Length: " + msg.arg1);
                // Check to see if message is the correct size
                if (msg.arg1 == 13) {
                    byte[] readBuf = (byte[]) msg.obj;

                    // Validate against checksum
                    int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8]
                            + readBuf[9] + readBuf[10];
                    if (calculatedCheckSum == readBuf[11]) {
                        // Convert to hex
                        String[] hexData = new String[13];
                        StringBuilder sbhex = new StringBuilder();
                        for (int i = 0; i < msg.arg1; i++) {
                            hexData[i] = String.format("%02X", readBuf[i]);
                            sbhex.append(hexData[i]);
                        }

                        // Get sensor position
                        String position = hexData[3];
                        // Get sensor ID
                        StringBuilder sensorID = new StringBuilder();
                        sensorID.append(hexData[4]);
                        sensorID.append(hexData[5]);
                        sensorID.append(hexData[6]);
                        sensorID.append(hexData[7]);

                        // Only parse message if there is one or more sensor mappings
                        String prefFrontID = sharedPrefs.getString("prefFrontID", "");
                        String prefRearID = sharedPrefs.getString("prefRearID", "");
                        try {
                            // Get temperature
                            int tempC = Integer.parseInt(hexData[8], 16) - 50;
                            double temp = tempC;
                            String temperatureUnit = "C";
                            // Get tire pressure
                            int psi = Integer.parseInt(hexData[9], 16);
                            double pressure = psi;
                            String pressureUnit = "psi";
                            // Get battery voltage
                            double voltage = Integer.parseInt(hexData[10], 16) / 50;
                            // Get pressure thresholds
                            int lowPressure = Integer.parseInt(sharedPrefs.getString("prefLowPressure", "30"));
                            int highPressure = Integer
                                    .parseInt(sharedPrefs.getString("prefHighPressure", "46"));
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                temp = (9.0 / 5.0) * tempC + 32.0;
                                temperatureUnit = "F";
                            }
                            int formattedTemperature = (int) (temp + 0.5d);
                            String pressureFormat = sharedPrefs.getString("prefPressureF", "0");
                            if (pressureFormat.contains("1")) {
                                // KPa
                                pressure = psi * 6.894757293168361;
                                pressureUnit = "KPa";
                            } else if (pressureFormat.contains("2")) {
                                // Kg-f
                                pressure = psi * 0.070306957965539;
                                pressureUnit = "Kg-f";
                            } else if (pressureFormat.contains("3")) {
                                // Bar
                                pressure = psi * 0.0689475729;
                                pressureUnit = "Bar";
                            }
                            int formattedPressure = (int) (pressure + 0.5d);
                            // Get checksum
                            String checksum = hexData[11];

                            if (Integer.parseInt(hexData[3], 16) <= 2) {
                                Log.d(TAG, "Front ID matched: " + Integer.parseInt(hexData[3], 16));

                                frontPressurePSI = psi;
                                // Set front tire status
                                if (psi <= lowPressure) {
                                    frontStatus = 1;
                                } else if (psi >= highPressure) {
                                    frontStatus = 2;
                                } else {
                                    frontStatus = 0;
                                }
                                if (sharedPrefs.getString("prefInfoView", "0").contains("2")) {
                                    txtFrontTPMS = (TextView) findViewById(R.id.textViewFrontTPMS);
                                    txtFrontTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
                                    txtFrontTPMS
                                            .setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    if (frontStatus != 0) {
                                        txtFrontTPMS.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        txtFrontTPMS
                                                .setTextColor(getResources().getColor(android.R.color.black));
                                    }
                                }
                            } else if (Integer.parseInt(hexData[3], 16) > 2) {
                                Log.d(TAG, "Rear ID matched: " + Integer.parseInt(hexData[3], 16));

                                rearPressurePSI = psi;
                                // Set rear tire status
                                if (psi <= lowPressure) {
                                    rearStatus = 4;
                                } else if (psi >= highPressure) {
                                    rearStatus = 5;
                                } else {
                                    rearStatus = 3;
                                }
                                if (sharedPrefs.getString("prefInfoView", "0").contains("2")) {
                                    txtRearTPMS = (TextView) findViewById(R.id.textViewRearTPMS);
                                    txtRearTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
                                    txtRearTPMS.setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    if (rearStatus != 3) {
                                        txtRearTPMS.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        txtRearTPMS
                                                .setTextColor(getResources().getColor(android.R.color.black));
                                    }
                                }
                            }
                            // Reset icon
                            if ((frontStatus == 0) && (rearStatus == 3)) {
                                imageButtonTPMS.setImageResource(R.mipmap.tpms_on);
                            }
                            if ((frontStatus != 0) || (rearStatus != 3)) {
                                imageButtonTPMS.setImageResource(R.mipmap.tpms_alert);
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(2));
                                editor.commit();

                                updateLayout();

                                int delay = (Integer
                                        .parseInt(sharedPrefs.getString("prefAudioAlertDelay", "30")) * 1000);
                                String currStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus));
                                if (alertTimer == 0) {
                                    alertTimer = System.currentTimeMillis();
                                } else {
                                    long currentTime = System.currentTimeMillis();
                                    long duration = (currentTime - alertTimer);
                                    if (!currStatus.equals(lastStatus) || duration >= delay) {
                                        alertTimer = 0;
                                        if ((frontStatus == 1) && (rearStatus == 3)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_lowFrontPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 3)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_highFrontPressure));
                                        } else if ((rearStatus == 4) && (frontStatus == 0)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_lowRearPressure));
                                        } else if ((rearStatus == 5) && (frontStatus == 0)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_highRearPressure));
                                        } else if ((frontStatus == 1) && (rearStatus == 4)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_lowFrontLowRearPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 5)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_highFrontHighRearPressure));
                                        } else if ((frontStatus == 1) && (rearStatus == 5)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_lowFrontHighRearPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 4)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_highFrontLowRearPressure));
                                        }
                                        lastStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus));
                                    }
                                }
                            }
                        } catch (NumberFormatException e) {
                            Log.d(TAG, "Malformed message, unexpected value");
                        }
                        if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                            // Log data
                            if (logger == null) {
                                logger = new LogData();
                            }
                            if (logger != null) {
                                logger.write(String.valueOf(sbhex));
                            }
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };

    // Sensor Stuff
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    Sensor magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    // Light
    if (lightSensor == null) {
        Log.d(TAG, "Light sensor not found");
    } else {
        sensorManager.registerListener(sensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
        hasSensor = true;
    }
    // Compass
    sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
    sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);

    // Try to connect to CANBusGateway
    canBusConnect();
    // Connect to iTPMS if enabled
    if (sharedPrefs.getBoolean("prefEnableTPMS", false)) {
        iTPMSConnect();
    }
}

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

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // Get rule//from   w w  w  . j  ava 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.msopentech.applicationgateway.EnterpriseBrowserActivity.java

public void showSettingsPopup(View v) {
    try {//from  www.j a v  a 2 s .  c o m
        PopupMenu popup = new PopupMenu(this, v);
        MenuInflater inflater = popup.getMenuInflater();
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                case R.id.menu_connection: {
                    showAgentsList();
                    return true;
                }
                case R.id.menu_sign_in_or_out: {
                    if (mIsSigninRequired) {
                        // Menu item in sign in mode.
                        //TODO: 
                        showSignIn(null, true);
                        return true;
                    }

                    // Clean up the session.
                    mTraits.sessionID = null;
                    mTraits.token = null;
                    mTraits.agent = null;

                    // Indicate the condition.
                    mIsSigninRequired = true;

                    //Remove all tabs except one.
                    mCustomTabHost.resetTabs();

                    mUrlEditTextView.setText("");

                    mProgressBarView.setProgress(0);

                    // Disable the reload button and set the right image for it.
                    mReloadButtonView.setEnabled(false);
                    mReloadButtonView.setImageResource(R.drawable.reload_button);

                    mStatusButtonView.setImageResource(R.drawable.connection_red);

                    // Since it's the user's intention to sign out, his
                    // history must be dropped.
                    PersistenceManager.dropContent(PersistenceManager.ContentType.HISTORY);

                    return true;
                }
                // Removed from RELEASE version. Should be active for development ONLY.                       
                //                        case R.id.menu_advanced_router_settings: {
                //                            showAdvancedRouterSettings(null);
                //                        }
                default: {
                    return false;
                }
                }
            }
        });
        inflater.inflate(R.menu.settings_menu, popup.getMenu());

        if (mIsSigninRequired) {
            MenuItem signItem = popup.getMenu().findItem(R.id.menu_sign_in_or_out);
            signItem.setTitle(getResources().getString(R.string.browser_menu_item_sign_in));
        }

        // Assumes that agent always has a display name. If display name is not present agent is considered to be not connected.
        MenuItem agentItem = popup.getMenu().findItem(R.id.menu_connection);
        String status = getResources().getString(R.string.browser_menu_item_choose_connection_not_connected);
        if (mTraits != null && mTraits.agent != null && !TextUtils.isEmpty(mTraits.agent.getDisplayName())) {
            status = mTraits.agent.getDisplayName();
        }
        Spannable span = new SpannableString(
                getResources().getString(R.string.browser_menu_item_choose_connection, status));
        span.setSpan(new RelativeSizeSpan(0.8f), 18, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.GRAY), 18, span.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        agentItem.setTitle(span);

        popup.show();
    } catch (final Exception e) {
        Utility.showAlertDialog(EnterpriseBrowserActivity.class.getSimpleName()
                + ".showSettingsPopup(): Failed. " + e.toString(), EnterpriseBrowserActivity.this);
    }
}

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

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // Get rule//  w ww  .  jav 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);
    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:android_network.hetnet.vpn_service.AdapterRule.java

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

    // Get rule/*from  w w  w  .  jav  a  2 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();

    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:com.zhengde163.netguard.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    //        Util.setTheme(this);
    setTheme(R.style.AppThemeBlue);//from  w ww  .ja v  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;
}