Example usage for android.os AsyncTask AsyncTask

List of usage examples for android.os AsyncTask AsyncTask

Introduction

In this page you can find the example usage for android.os AsyncTask AsyncTask.

Prototype

public AsyncTask() 

Source Link

Document

Creates a new asynchronous task.

Usage

From source file:eu.operando.operandoapp.filters.domain.DomainFiltersActivity.java

protected void importExternalFilters(final String importUrl) {
    final File tmp = new File(getFilesDir(), "domainfilters_" + System.currentTimeMillis());
    try {/*from w ww  . j  a va  2s  .c om*/
        new DownloadTask(DomainFiltersActivity.this, new URL(importUrl), tmp, new DownloadTask.Listener() {
            @Override
            public void onCompleted() {
                //Toast.makeText(DomainFiltersActivity.this, R.string.msg_downloaded, Toast.LENGTH_LONG).show();

                new AsyncTask<Void, Void, Integer>() {

                    ProgressDialog dialog;

                    @Override
                    protected void onPreExecute() {
                        dialog = ProgressDialog.show(DomainFiltersActivity.this, null,
                                "Parsing downloaded file...");
                        dialog.setCancelable(false);
                    }

                    @Override
                    protected Integer doInBackground(Void... params) {
                        Integer count = 0;
                        BufferedReader br = null;
                        try {
                            br = new BufferedReader(new FileReader(tmp));
                            String line;
                            while ((line = br.readLine()) != null) {
                                int hash = line.indexOf('#');
                                if (hash >= 0)
                                    line = line.substring(0, hash);
                                line = line.trim();
                                try {
                                    String blockedDomain = line;
                                    if (blockedDomain.equals("local") || StringUtils.containsAny(blockedDomain,
                                            "localhost", "127.0.0.1", "broadcasthost"))
                                        continue;
                                    DomainFilter domainFilter = new DomainFilter();
                                    domainFilter.setContent(blockedDomain);
                                    domainFilter.setSource(importUrl);
                                    domainFilter.setIsWildcard(false);
                                    db.createDomainFilter(domainFilter);
                                    count++;
                                } catch (Exception e) {
                                    Log.i(TAG, "Invalid hosts file line: " + line);
                                }
                            }
                            Log.i(TAG, count + " entries read");
                        } catch (IOException ex) {
                            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        } finally {
                            if (br != null)
                                try {
                                    br.close();
                                } catch (IOException exex) {
                                    Log.e(TAG, exex.toString() + "\n" + Log.getStackTraceString(exex));
                                }
                        }

                        return count;
                    }

                    @Override
                    protected void onPostExecute(Integer count) {
                        dialog.dismiss();
                        if (count > 0) {
                            updateFiltersList();
                            externalDomainFiltersAdapter.notifyDataSetChanged();
                        }
                    }
                }.execute();
            }

            @Override
            public void onCancelled() {
                if (tmp.exists())
                    tmp.delete();
            }

            @Override
            public void onException(Throwable ex) {
                if (tmp.exists())
                    tmp.delete();

                ex.printStackTrace();
                Toast.makeText(DomainFiltersActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();
            }
        }).execute();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Toast.makeText(DomainFiltersActivity.this, ex.toString(), Toast.LENGTH_LONG).show();
    }
}

From source file:com.concentricsky.android.khanacademy.data.KADataService.java

private void updateDownloadStatus(Intent intent, final PendingIntent pendingIntent, final int startId) {
    final long id = intent.getLongExtra(EXTRA_ID, -1);
    final DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    final DownloadManager.Query q = new DownloadManager.Query();
    q.setFilterById(id);//from   w ww  .j a  va2 s  .c o m

    new AsyncTask<Void, Void, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... arg) {
            Cursor cursor = mgr.query(q);
            String youtubeId = null;
            int status = -1;
            if (cursor.moveToFirst()) {
                String filename = cursor
                        .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                youtubeId = OfflineVideoManager.youtubeIdFromFilename(filename);
                status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
            cursor.close();

            if (status == DownloadManager.STATUS_SUCCESSFUL && youtubeId != null) {
                try {
                    Dao<Video, String> videoDao = helper.getVideoDao();
                    UpdateBuilder<Video, String> q = videoDao.updateBuilder();
                    q.where().eq("youtube_id", youtubeId);
                    q.updateColumnValue("download_status", Video.DL_STATUS_COMPLETE);
                    q.update();
                    return true;
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            return false;
        }

        @Override
        protected void onPostExecute(Boolean successful) {
            if (successful) {
                broadcastOfflineVideoSetChanged();
                finish(startId, pendingIntent, RESULT_SUCCESS);
            } else {
                finish(startId, pendingIntent, RESULT_ERROR);
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

}

From source file:org.anhonesteffort.flock.SubscriptionStripeFragment.java

private void handleVerifyCardAndPutToServer() {
    if (asyncTask != null)
        return;//from   ww  w  .j  a va 2  s .c o  m

    asyncTask = new AsyncTask<Void, Void, Bundle>() {

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "handleVerifyCardAndPutToServer()");
            subscriptionActivity.setProgressBarIndeterminateVisibility(true);
            subscriptionActivity.setProgressBarVisibility(true);
        }

        private String handleGetStripeCardTokenId(String cardNumber, String cardExpiration, String cardCVC)
                throws StripeException {
            String[] expiration = cardExpiration.split("/");
            Integer expirationMonth = Integer.valueOf(expiration[0]);
            Integer expirationYear;

            if (expiration[1].length() == 4)
                expirationYear = Integer.valueOf(expiration[1]);
            else
                expirationYear = Integer.valueOf(expiration[1]) + 2000;

            java.util.Map<String, Object> cardParams = new HashMap<String, Object>();
            java.util.Map<String, Object> tokenParams = new HashMap<String, Object>();

            cardParams.put("number", cardNumber.replace(" ", ""));
            cardParams.put("exp_month", expirationMonth);
            cardParams.put("exp_year", expirationYear);
            cardParams.put("cvc", cardCVC);

            tokenParams.put("card", cardParams);

            return Token.create(tokenParams, OwsRegistration.STRIPE_PUBLIC_KEY).getId();
        }

        private void handlePutStripeTokenToServer(String stripeTokenId)
                throws IOException, RegistrationApiException, CardException {
            RegistrationApi registrationApi = new RegistrationApi(subscriptionActivity);
            registrationApi.setStripeCard(subscriptionActivity.davAccount, stripeTokenId);
        }

        private void handleUpdateSubscriptionStore(String cardNumber, String cardExpiration)
                throws JsonProcessingException {
            String cardNoSpaces = cardNumber.replace(" ", "");
            String lastFour = cardNoSpaces.substring(cardNoSpaces.length() - 4);

            FlockCardInformation cardInformation = new FlockCardInformation(
                    subscriptionActivity.davAccount.getUserId(), lastFour, cardExpiration);

            StripePlan newStripePlan = new StripePlan(subscriptionActivity.davAccount.getUserId(), "nope");

            AccountStore.setLastChargeFailed(subscriptionActivity, false);
            AccountStore.setSubscriptionPlan(subscriptionActivity, newStripePlan);
            AccountStore.setAutoRenew(subscriptionActivity, true);
            AccountStore.setCardInformation(subscriptionActivity, Optional.of(cardInformation));
        }

        @Override
        protected Bundle doInBackground(Void... params) {
            Bundle result = new Bundle();
            String cardNumber = ((TextView) subscriptionActivity.findViewById(R.id.card_number)).getText()
                    .toString();
            String cardExpiration = ((TextView) subscriptionActivity.findViewById(R.id.card_expiration))
                    .getText().toString();
            String cardCVC = ((TextView) subscriptionActivity.findViewById(R.id.card_cvc)).getText().toString();

            if (StringUtils.isEmpty(cardNumber) || cardNumber.contains("*")) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_NUMBER_INVALID);
                return result;
            }

            if (StringUtils.isEmpty(cardExpiration) || cardExpiration.split("/").length != 2) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_EXPIRATION_INVALID);
                return result;
            }

            if (StringUtils.isEmpty(cardCVC) || cardCVC.length() < 1) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_CVC_INVALID);
                return result;
            }

            try {

                String stripeTokenId = handleGetStripeCardTokenId(cardNumber, cardExpiration, cardCVC);
                handlePutStripeTokenToServer(stripeTokenId);
                handleUpdateSubscriptionStore(cardNumber, cardExpiration);

                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

            } catch (CardException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (StripeException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (RegistrationApiException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (JsonProcessingException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (IOException e) {
                ErrorToaster.handleBundleError(e, result);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            asyncTask = null;
            subscriptionActivity.setProgressBarIndeterminateVisibility(false);
            subscriptionActivity.setProgressBarVisibility(false);

            if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS) {
                Toast.makeText(subscriptionActivity, R.string.card_verified_and_saved, Toast.LENGTH_LONG)
                        .show();
                handleUpdateUi();
            }

            else {
                ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result);
                handleUpdateUi();
            }
        }
    }.execute();
}

From source file:com.example.carrie.carrie_test1.druginfo.java

private void load_data_from_server_notsearch(int id) {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override//from  w  w  w.j  a  va2 s.  co m
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://54.65.194.253/Drug/ShowDrug.php?id=" + integers[0]).build();
            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(response.body().string());

                for (int i = 0; i < array.length(); i++) {

                    JSONObject object = array.getJSONObject(i);

                    MyData mydata = new MyData(object.getInt("id"), object.getString("chineseName"),
                            object.getString("image"), object.getString("indication"),
                            object.getString("englishName"), object.getString("licenseNumber"),
                            object.getString("category"), object.getString("component"),
                            object.getString("maker_Country"), object.getString("applicant"),
                            object.getString("maker_Name"), object.getString("QRCode"));

                    data_list1.add(mydata);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                System.out.println("End of content");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            adapter.notifyDataSetChanged();
        }
    };

    task.execute(id);
}

From source file:com.df.push.DemoActivity.java

/**
 * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
 * messages to your app. Not needed for this demo since the device sends upstream messages
 * to a server that echoes back the message using the 'from' address in the message.
 *//*from  w  ww . j  a  v a  2  s .c om*/
private void sendRegistrationIdToBackend(final String regId) {
    // Dreamfactory server url
    final String url = "https://next.cloud.dreamfactory.com/rest/sns/app/662443008147:app/GCM/com.dreamfactory.launchpad/endpoint?app_name=todoangular";
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            JSONObject obj = new JSONObject();
            try {
                obj.put("Token", regId);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            Log.i(TAG, "Device registration request data " + obj.toString());
            // Your implementation here.
            HttpResponse<JsonNode> jsonResponse;
            try {
                jsonResponse = Unirest.post(url).header("accept", "application/json").body(obj.toString())
                        .asJson();
                String endPoint = jsonResponse.getBody().getObject().getString("EndpointArn");
                Log.i(TAG, "Device registration response " + jsonResponse.getBody().getObject().toString());
                msg = null;
                final SharedPreferences prefs = getGcmPreferences(context);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString(PROPERTY_REG_URL, endPoint);
                editor.commit();
            } catch (Exception e) {
                msg = e.getLocalizedMessage();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            if (msg == null) {
                findViewById(R.id.subscribe).setVisibility(View.VISIBLE);
                findViewById(R.id.unsubscribe).setVisibility(View.VISIBLE);
            } else {
                mDisplay.append(msg + "\n");
            }
            progressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            if (progressDialog != null)
                progressDialog.show();
        };
    }.execute(null, null, null);
}

From source file:com.svo.library.widget.RLWebBrowser.java

public void getDownUrls(String url) {
    new AsyncTask<String, String, ArrayList<String>>() {
        @Override/* w w w  .j  a v a2  s .  co m*/
        protected ArrayList<String> doInBackground(String... params) {
            ArrayList<String> urls = new ArrayList<String>();
            String html = getRequest(params[0]);
            Pattern pattern = Pattern
                    .compile("http:[^><]*?\\.(?i)(torrent|mp4|wmv|3gp|avi|rmvb|rm|mkv)|thunder:(.|\\s)+?=+");
            Matcher matcher = pattern.matcher(html);
            while (matcher.find()) {
                urls.add(matcher.group());
            }
            return urls;
        }

        protected void onPostExecute(ArrayList<String> result) {
            downUrlsListener.result(result);
        };
    }.execute(url);
}

From source file:com.etalio.android.EtalioBase.java

/**
 * Requests an access token and a refresh token from Etalio
 *//*from   w  w w  .j a  va  2s .  c  o  m*/
protected void authorizeAndAcquireTokensFromCallback(final Intent intent, final AuthenticationCallback callback)
        throws EtalioAuthorizationCodeException {
    if (!isEtalioSignInCallback(intent)) {
        throw new IllegalArgumentException("The intent does not contain a valid authentication callback.");
    }
    //set the code for later
    final String code = getAuthorizationCodeFromUri(intent.getData());
    //Reset intent data to not trigger this call again.
    if (intent != null) {
        intent.setData(null);
    }

    new AsyncTask<String, Void, Boolean>() {

        public EtalioTokenException error;

        @Override
        protected Boolean doInBackground(String... params) {
            //get and set the access/refresh tokens
            try {
                requestNewToken(params[0]);
            } catch (EtalioTokenException e) {
                this.error = e;
                return false;
            } catch (IOException e) {
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (callback != null) {
                if (result) {
                    callback.onAuthenticationSuccess();
                } else {
                    callback.onAuthenticationFailure(this.error);
                }
            }
        }
    }.execute(code);
}

From source file:com.firescar96.nom.GCMIntentService.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>/*from  w  w w . jav  a  2  s  . c  o m*/
 * Stores the registration ID and app versionCode in the application's
 * shared preferences.
 */
public static void registerInBackground() {
    new AsyncTask<Object, Object, Object>() {
        @Override
        protected String doInBackground(Object... params) {
            String msg = "";
            try {
                if (gcm == null)
                    gcm = GoogleCloudMessaging.getInstance(context);
                regId = gcm.register(SENDER_ID);
                msg = "Device registered, registration ID=" + regId;

                // You should send the registration ID to your server over HTTP,
                // so it can use GCM/HTTP or CCS to send messages to your app.
                // The request to your server should be authenticated if your app
                // is using accounts.
                System.out.println("regID: " + regId);
                if (MainActivity.appData.getString("host").length() > 0)
                    sendRegistrationIdToBackend();

                // For this demo: we don't need to send it because the device
                // will send upstream messages to a server that echo back the
                // message using the 'from' address in the message.

                // Persist the regID - no need to register again.
                storeRegistrationId(context, regId);
            } catch (IOException | JSONException ex) {
                msg = "Error :" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }

            System.out.println(msg);
            return msg;
        }

    }.execute(null, null, null);
}

From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java

/**
 * ???./*  ww  w  .j av  a  2  s  .  c o  m*/
 * 
 * @param deviceId ?ID
 * @param timeslice 
 * @param listener 
 */
public static void asyncStartMovie(final String deviceId, final long timeslice,
        final DConnectMessageHandler listener) {
    AsyncTask<Void, Void, DConnectMessage> task = new AsyncTask<Void, Void, DConnectMessage>() {
        @Override
        protected DConnectMessage doInBackground(final Void... params) {
            try {
                DConnectClient client = new HttpDConnectClient();
                HttpPost request = new HttpPost(
                        MEDIASTREAM_RECORD + "?deviceId=" + deviceId + "&timeslice=" + timeslice);
                HttpResponse response = client.execute(request);
                return (new HttpMessageFactory()).newDConnectMessage(response);
            } catch (IOException e) {
                return new DConnectResponseMessage(DConnectMessage.RESULT_ERROR);
            }
        }

        @Override
        protected void onPostExecute(final DConnectMessage message) {
            if (listener != null) {
                listener.handleMessage(message);
            }
        }
    };
    task.execute();
}

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// w  w  w  .  j av  a 2 s  . com
    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);
        }
    });
}