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:uk.bowdlerize.MainActivity.java

private void sendRegistrationIdToBackend() {
    new AsyncTask<Void, Void, Boolean>() {
        @Override//from w w w  . ja v  a2 s.c o m
        protected Boolean doInBackground(Void... params) {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            JSONObject json;
            HttpPost httpost = new HttpPost("https://bowdlerize.co.uk/api/1/updategcm.php");

            httpost.setHeader("Accept", "application/json");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("gcmid", regid));
            nvps.add(new BasicNameValuePair("deviceid",
                    MD5(Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID))));

            try {
                httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

                HttpResponse response = httpclient.execute(httpost);
                String rawJSON = EntityUtils.toString(response.getEntity());
                response.getEntity().consumeContent();
                Log.e("rawJSON", rawJSON);
                json = new JSONObject(rawJSON);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            //TODO if it fails we should reregister
        }
    }.execute(null, null, null);
}

From source file:com.otaupdater.utils.Utils.java

public static void updateDeviceRegistration(final Context ctx) {
    final Config cfg = Config.getInstance(ctx);

    final APIUtils.APIAdapter regCallback = new APIUtils.APIAdapter() {
        @Override/*from www.  j  a v  a2  s  . c  o  m*/
        public void onSuccess(String message, JSONObject respObj) {
            cfg.setPingedCurrent();

            if (PropUtils.isRomOtaEnabled()) {
                RomInfo info = RomInfo.FACTORY.fromJSON(respObj.optJSONObject(RomInfo.KEY_NAME));
                if (info != null && info.isUpdate()) {
                    cfg.storeRomUpdate(info);
                    if (cfg.getShowNotif()) {
                        info.showUpdateNotif(ctx);
                    } else {
                        Log.v(Config.LOG_TAG + "DeviceRegister", "got rom update response, notif not shown");
                    }
                } else {
                    cfg.clearStoredRomUpdate();
                    RomInfo.FACTORY.clearUpdateNotif(ctx);
                }
            }

            if (PropUtils.isKernelOtaEnabled()) {
                KernelInfo info = KernelInfo.FACTORY.fromJSON(respObj.optJSONObject(KernelInfo.KEY_NAME));
                if (info != null && info.isUpdate()) {
                    cfg.storeKernelUpdate(info);
                    if (cfg.getShowNotif()) {
                        info.showUpdateNotif(ctx);
                    } else {
                        Log.v(Config.LOG_TAG + "DeviceRegister", "got kernel update response, notif not shown");
                    }
                } else {
                    cfg.clearStoredKernelUpdate();
                    KernelInfo.FACTORY.clearUpdateNotif(ctx);
                }
            }
        }

        @Override
        public void onError(String message, JSONObject respObj) {
            cfg.setGcmRegistrationId(null); //TODO maybe do something better?
            Log.w(Config.LOG_TAG + "DeviceRegister", "error registering with server: " + message);
        }
    };

    if (checkPlayServices(ctx)) {
        String regId = cfg.getGcmRegistrationId();
        if (regId == null) {
            Log.v(Config.LOG_TAG + "DeviceRegister", "Not registered, registering for GCM...");
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    try {
                        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(ctx);
                        String regID = gcm.register(Config.GCM_SENDER_ID);

                        cfg.setGcmRegistrationId(regID);
                        Log.v(Config.LOG_TAG + "DeviceRegister", "GCM registered");

                        APIUtils.updateDeviceRegistration(ctx, regCallback);
                    } catch (Exception ex) {
                        Log.e(Config.LOG_TAG + "DeviceRegister", "Error registering GCM: " + ex.getMessage());
                    }
                    return null;
                }
            }.execute();
        } else if (!cfg.upToDate()) {
            Log.v(Config.LOG_TAG + "DeviceRegister", "Already GCM registered, out-of-date");
            cfg.setValuesToCurrent();
            APIUtils.updateDeviceRegistration(ctx, regCallback);
        } else if (cfg.needPing()) {
            Log.v(Config.LOG_TAG + "DeviceRegister", "Already GCM registered, need to ping");
            APIUtils.doPing(ctx, new APIUtils.APIAdapter() {
                @Override
                public void onSuccess(String message, JSONObject respObj) {
                    cfg.setPingedCurrent();
                }
            });
        } else {
            Log.v(Config.LOG_TAG + "DeviceRegister", "Already GCM registered, no ping necessary");
        }
    } else if (!cfg.upToDate()) {
        Log.v(Config.LOG_TAG + "DeviceRegister", "Already registered, out-of-date");
        cfg.setValuesToCurrent();
        APIUtils.updateDeviceRegistration(ctx, regCallback);
    } else if (cfg.needPing()) {
        Log.v(Config.LOG_TAG + "DeviceRegister", "Already registered, need to ping");
        APIUtils.doPing(ctx, new APIUtils.APIAdapter() {
            @Override
            public void onSuccess(String message, JSONObject respObj) {
                cfg.setPingedCurrent();
            }
        });
    } else {
        Log.v(Config.LOG_TAG + "DeviceRegister", "Already registered, no ping necessary");
    }
}

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

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    final PreferenceScreen screen = getPreferenceScreen();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    PreferenceGroup cat_options = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_options"))
            .findPreference("category_options");
    PreferenceGroup cat_advanced = (PreferenceGroup) ((PreferenceGroup) screen
            .findPreference("screen_advanced_options")).findPreference("category_advanced_options");
    PreferenceGroup cat_stats = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_stats"))
            .findPreference("category_stats");
    PreferenceGroup cat_backup = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_backup"))
            .findPreference("category_backup");

    // Handle auto enable
    Preference pref_auto_enable = screen.findPreference("auto_enable");
    pref_auto_enable.setTitle(getString(R.string.setting_auto, prefs.getString("auto_enable", "0")));

    // Handle screen delay
    Preference pref_screen_delay = screen.findPreference("screen_delay");
    pref_screen_delay.setTitle(getString(R.string.setting_delay, prefs.getString("screen_delay", "0")));

    // Handle theme
    Preference pref_screen_theme = screen.findPreference("theme");
    String theme = prefs.getString("theme", "teal");
    String[] themeNames = getResources().getStringArray(R.array.themeNames);
    String[] themeValues = getResources().getStringArray(R.array.themeValues);
    for (int i = 0; i < themeNames.length; i++)
        if (theme.equals(themeValues[i])) {
            pref_screen_theme.setTitle(getString(R.string.setting_theme, themeNames[i]));
            break;
        }/* ww  w .j a va 2 s .c om*/

    // Wi-Fi home
    MultiSelectListPreference pref_wifi_homes = (MultiSelectListPreference) screen.findPreference("wifi_homes");
    Set<String> ssids = prefs.getStringSet("wifi_homes", new HashSet<String>());
    if (ssids.size() > 0)
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, TextUtils.join(", ", ssids)));
    else
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, "-"));

    WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    List<CharSequence> listSSID = new ArrayList<>();
    List<WifiConfiguration> configs = wm.getConfiguredNetworks();
    if (configs != null)
        for (WifiConfiguration config : configs)
            listSSID.add(config.SSID == null ? "NULL" : config.SSID);
    for (String ssid : ssids)
        if (!listSSID.contains(ssid))
            listSSID.add(ssid);
    pref_wifi_homes.setEntries(listSSID.toArray(new CharSequence[0]));
    pref_wifi_homes.setEntryValues(listSSID.toArray(new CharSequence[0]));

    Preference pref_reset_usage = screen.findPreference("reset_usage");
    pref_reset_usage.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.areYouSure(ActivitySettings.this, R.string.setting_reset_usage, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    new AsyncTask<Object, Object, Throwable>() {
                        @Override
                        protected Throwable doInBackground(Object... objects) {
                            try {
                                DatabaseHelper.getInstance(ActivitySettings.this).resetUsage(-1);
                                return null;
                            } catch (Throwable ex) {
                                return ex;
                            }
                        }

                        @Override
                        protected void onPostExecute(Throwable ex) {
                            if (ex == null)
                                Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG)
                                        .show();
                            else
                                Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                        }
                    }.execute();
                }
            });
            return false;
        }
    });

    // Handle port forwarding
    Preference pref_forwarding = screen.findPreference("forwarding");
    pref_forwarding.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityForwarding.class));
            return true;
        }
    });

    // VPN parameters
    screen.findPreference("vpn4")
            .setTitle(getString(R.string.setting_vpn4, prefs.getString("vpn4", "10.1.10.1")));
    screen.findPreference("vpn6")
            .setTitle(getString(R.string.setting_vpn6, prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1")));
    EditTextPreference pref_dns1 = (EditTextPreference) screen.findPreference("dns");
    EditTextPreference pref_dns2 = (EditTextPreference) screen.findPreference("dns2");
    EditTextPreference pref_ttl = (EditTextPreference) screen.findPreference("ttl");
    List<String> def_dns = Util.getDefaultDNS(this);
    pref_dns1.getEditText().setHint(def_dns.get(0));
    pref_dns2.getEditText().setHint(def_dns.get(1));
    pref_dns1.setTitle(getString(R.string.setting_dns, prefs.getString("dns", def_dns.get(0))));
    pref_dns2.setTitle(getString(R.string.setting_dns, prefs.getString("dns2", def_dns.get(1))));
    pref_ttl.setTitle(getString(R.string.setting_ttl, prefs.getString("ttl", "259200")));

    // SOCKS5 parameters
    screen.findPreference("socks5_addr")
            .setTitle(getString(R.string.setting_socks5_addr, prefs.getString("socks5_addr", "-")));
    screen.findPreference("socks5_port")
            .setTitle(getString(R.string.setting_socks5_port, prefs.getString("socks5_port", "-")));
    screen.findPreference("socks5_username")
            .setTitle(getString(R.string.setting_socks5_username, prefs.getString("socks5_username", "-")));
    screen.findPreference("socks5_password").setTitle(getString(R.string.setting_socks5_password,
            TextUtils.isEmpty(prefs.getString("socks5_username", "")) ? "-" : "*****"));

    // PCAP parameters
    screen.findPreference("pcap_record_size")
            .setTitle(getString(R.string.setting_pcap_record_size, prefs.getString("pcap_record_size", "64")));
    screen.findPreference("pcap_file_size")
            .setTitle(getString(R.string.setting_pcap_file_size, prefs.getString("pcap_file_size", "2")));

    // Watchdog
    screen.findPreference("watchdog")
            .setTitle(getString(R.string.setting_watchdog, prefs.getString("watchdog", "0")));

    // Show resolved
    Preference pref_show_resolved = screen.findPreference("show_resolved");
    if (Util.isPlayStoreInstall(this))
        cat_advanced.removePreference(pref_show_resolved);
    else
        pref_show_resolved.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(new Intent(ActivitySettings.this, ActivityDns.class));
                return true;
            }
        });

    // Handle stats
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        cat_stats.removePreference(screen.findPreference("show_top"));
    EditTextPreference pref_stats_frequency = (EditTextPreference) screen.findPreference("stats_frequency");
    EditTextPreference pref_stats_samples = (EditTextPreference) screen.findPreference("stats_samples");
    pref_stats_frequency
            .setTitle(getString(R.string.setting_stats_frequency, prefs.getString("stats_frequency", "1000")));
    pref_stats_samples
            .setTitle(getString(R.string.setting_stats_samples, prefs.getString("stats_samples", "90")));

    // Handle export
    Preference pref_export = screen.findPreference("export");
    pref_export.setEnabled(getIntentCreateExport().resolveActivity(getPackageManager()) != null);
    pref_export.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentCreateExport(), ActivitySettings.REQUEST_EXPORT);
            return true;
        }
    });

    // Handle import
    Preference pref_import = screen.findPreference("import");
    pref_import.setEnabled(getIntentOpenExport().resolveActivity(getPackageManager()) != null);
    pref_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentOpenExport(), ActivitySettings.REQUEST_IMPORT);
            return true;
        }
    });

    // Hosts file settings
    Preference pref_block_domains = screen.findPreference("use_hosts");
    EditTextPreference pref_rcode = (EditTextPreference) screen.findPreference("rcode");
    Preference pref_hosts_import = screen.findPreference("hosts_import");
    EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
    final Preference pref_hosts_download = screen.findPreference("hosts_download");

    pref_rcode.setTitle(getString(R.string.setting_rcode, prefs.getString("rcode", "3")));

    if (Util.isPlayStoreInstall(this)) {
        Log.i(TAG, "Play store install");
        cat_options.removePreference(screen.findPreference("update_check"));
        cat_advanced.removePreference(pref_block_domains);
        cat_advanced.removePreference(pref_rcode);
        cat_advanced.removePreference(pref_forwarding);
        cat_backup.removePreference(pref_hosts_import);
        cat_backup.removePreference(pref_hosts_url);
        cat_backup.removePreference(pref_hosts_download);

    } else {
        String last_import = prefs.getString("hosts_last_import", null);
        String last_download = prefs.getString("hosts_last_download", null);
        if (last_import != null)
            pref_hosts_import.setSummary(getString(R.string.msg_import_last, last_import));
        if (last_download != null)
            pref_hosts_download.setSummary(getString(R.string.msg_download_last, last_download));

        // Handle hosts import
        // https://github.com/Free-Software-for-Android/AdAway/wiki/HostsSources
        pref_hosts_import.setEnabled(getIntentOpenHosts().resolveActivity(getPackageManager()) != null);
        pref_hosts_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivityForResult(getIntentOpenHosts(), ActivitySettings.REQUEST_HOSTS);
                return true;
            }
        });

        // Handle hosts file download
        pref_hosts_url.setSummary(pref_hosts_url.getText());
        pref_hosts_download.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                final File tmp = new File(getFilesDir(), "hosts.tmp");
                final File hosts = new File(getFilesDir(), "hosts.txt");
                EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
                try {
                    new DownloadTask(ActivitySettings.this, new URL(pref_hosts_url.getText()), tmp,
                            new DownloadTask.Listener() {
                                @Override
                                public void onCompleted() {
                                    if (hosts.exists())
                                        hosts.delete();
                                    tmp.renameTo(hosts);

                                    String last = SimpleDateFormat.getDateTimeInstance()
                                            .format(new Date().getTime());
                                    prefs.edit().putString("hosts_last_download", last).apply();

                                    if (running) {
                                        pref_hosts_download
                                                .setSummary(getString(R.string.msg_download_last, last));
                                        Toast.makeText(ActivitySettings.this, R.string.msg_downloaded,
                                                Toast.LENGTH_LONG).show();
                                    }

                                    ServiceSinkhole.reload("hosts file download", ActivitySettings.this);
                                }

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

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

                                    if (running)
                                        Toast.makeText(ActivitySettings.this, ex.getMessage(),
                                                Toast.LENGTH_LONG).show();
                                }
                            }).execute();
                } catch (MalformedURLException ex) {
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                }
                return true;
            }
        });
    }

    // Development
    if (!Util.isDebuggable(this))
        screen.removePreference(screen.findPreference("screen_development"));

    // Handle technical info
    Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            updateTechnicalInfo();
            return true;
        }
    };

    // Technical info
    Preference pref_technical_info = screen.findPreference("technical_info");
    Preference pref_technical_network = screen.findPreference("technical_network");
    Preference pref_technical_subscription = screen.findPreference("technical_subscription");
    pref_technical_info.setEnabled(INTENT_VPN_SETTINGS.resolveActivity(this.getPackageManager()) != null);
    pref_technical_info.setIntent(INTENT_VPN_SETTINGS);
    pref_technical_info.setOnPreferenceClickListener(listener);
    pref_technical_network.setOnPreferenceClickListener(listener);
    pref_technical_subscription.setOnPreferenceClickListener(listener);
    updateTechnicalInfo();

    //        markPro(screen.findPreference("theme"), ActivityPro.SKU_THEME);
    //        markPro(screen.findPreference("install"), ActivityPro.SKU_NOTIFY);
    //        markPro(screen.findPreference("show_stats"), ActivityPro.SKU_SPEED);
}

From source file:com.shafiq.myfeedle.core.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);/*  w  ww. ja v  a2s .  c o m*/
    mHttpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Myfeedle.Accounts.SERVICE, Myfeedle.INVALID_SERVICE);
            mServiceName = Myfeedle.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Myfeedle.EXTRA_ACCOUNT_ID, Myfeedle.INVALID_ACCOUNT_ID);
            mMyfeedleWebView = new MyfeedleWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mMyfeedleOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mMyfeedleWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mMyfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mMyfeedleWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID,
                        FACEBOOK_CALLBACK.toString()));
                break;
            // case MYSPACE:
            //     mMyfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET);
            //     asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case FOURSQUARE:
                mMyfeedleWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mMyfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Myfeedle.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            // case IDENTICA:
            //     mMyfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET);
            //     asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case GOOGLEPLUS:
                mMyfeedleWebView.open(
                        String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob"));
                break;
            // case CHATTER:
            //     mMyfeedleWebView.open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString()));
            //     break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:com.windigo.RestApiMethodMetadata.java

/**
 * Make requests asyncronously with {@link AsyncTask} and return {@link HttpResponse}
 *
 * @param url/*w w  w. j a v  a2 s.  c  o  m*/
 * @param parameters
 * @return {@link HttpResponse}
 * @throws InterruptedException
 * @throws ExecutionException
 */
public Object makeAsyncRequest(final Request request)
        throws IOException, InterruptedException, ExecutionException {

    AsyncTask<Void, Integer, Object> backgroundTask = new AsyncTask<Void, Integer, Object>() {
        Response response;
        Object typedResponseObject;

        @Override
        protected Object doInBackground(Void... params) {
            try {
                response = httpClient.execute(request);

                if (response != null) {
                    response.setContentParser(typeParser);
                    typedResponseObject = typeParser.parse(response.getContentStream());
                    Logger.log("[Response] Typed response object: " + typedResponseObject.toString());
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JsonConversionException e) {
                e.printStackTrace();
            }
            return typedResponseObject;
        }

    }.execute();

    return backgroundTask.get();
}

From source file:ca.etsmtl.applets.etsmobile.ProfileActivity.java

private void getBandwith(String phase, String appt) {
    appt_input.setEnabled(false);/*w w w. j a  v  a 2s.  c om*/
    phase_input.setEnabled(false);

    final Editor edit = prefs.edit();
    creds.setPhase(phase);
    creds.setAppt(appt);
    edit.putString(UserCredentials.REZ, phase);
    edit.putString(UserCredentials.APPT, appt);
    edit.commit();

    // get bandwidth from cooptel, parse html, extract floats, etc etc
    new AsyncTask<String, Void, float[]>() {
        final Pattern usageRegex = Pattern.compile(
                "<TR><TD>(.*)</TD><TD>(.*)</TD><TD ALIGN=\"RIGHT\">(.*)</TD><TD ALIGN=\"RIGHT\">(.*)</TD></TR>");
        final Pattern quotaRegex = Pattern.compile(
                "<TR><TD>Quota permis pour la p&eacute;riode</TD><TD ALIGN=\"RIGHT\">(.*)</TD></TD></TR>");

        @Override
        protected float[] doInBackground(String... params) {
            final float[] result = new float[2];
            try {
                final HttpGet get = new HttpGet(URI.create(
                        String.format("http://www2.cooptel.qc.ca/services/temps/?mois=%d&cmd=Visualiser",
                                Calendar.getInstance().get(Calendar.MONTH) + 1)));
                final BasicScheme scheme = new BasicScheme();
                final Credentials credentials = new UsernamePasswordCredentials(
                        "ets-res" + params[0] + "-" + params[1], "ets" + params[1]);
                try {
                    final Header h = scheme.authenticate(credentials, get);
                    get.addHeader(h);
                    final HttpClient client = new DefaultHttpClient();
                    final HttpResponse re = client.execute(get);

                    // if HTTP200
                    if (re.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        final String ent = EntityUtils.toString(re.getEntity());
                        final Matcher matcher = usageRegex.matcher(ent);

                        float total = 0;
                        // String[] usageResult = matcher.;
                        // parse all results
                        while (matcher.find()) {
                            final Number upload = Float.parseFloat(matcher.group(3));
                            final Number download = Float.parseFloat(matcher.group(4));

                            total += upload.floatValue();
                            total += download.floatValue();
                        }

                        final Matcher quotaResult = quotaRegex.matcher(ent);
                        float totalBandwithAvail = 0;
                        if (quotaResult.find()) {
                            totalBandwithAvail = Float.parseFloat(quotaResult.group(1));
                        }
                        result[0] = total / 1024;
                        result[1] = totalBandwithAvail / 1024;

                    }
                } catch (final AuthenticationException e) {
                    e.printStackTrace();
                }

            } catch (final IOException e) {
                e.printStackTrace();
            }

            return result;
        }

        @Override
        protected void onPostExecute(float[] result) {
            handlerBandwith.obtainMessage(2, result).sendToTarget();
            super.onPostExecute(result);
        }

    }.execute(phase, appt);
}

From source file:com.bellman.bible.android.view.activity.base.DocumentSelectionBase.java

protected void populateMasterDocumentList(final boolean refresh) {
    Log.d(TAG, "populate Master Document List");

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

        @Override/* w w  w .  ja  v  a  2 s .co m*/
        protected void onPreExecute() {
            showHourglass();
            showPreLoadMessage();
        }

        @Override
        protected Void doInBackground(Void... noparam) {
            try {
                // Prevent occasional class loading errors on Samsung devices
                Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

                allDocuments = getDocumentsFromSource(refresh);
                Log.i(TAG, "number of documents:" + allDocuments.size());
            } catch (Exception e) {
                Log.e(TAG, "Error getting documents", e);
                Dialogs.getInstance().showErrorMsg(R.string.error_occurred, e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            try {
                if (allDocuments != null) {
                    populateLanguageList();

                    // default language depends on doc availability so must do in onPostExecute
                    setDefaultLanguage();
                    filterDocuments();
                }
            } finally {
                //todo implement this: http://stackoverflow.com/questions/891451/android-dismissdialog-does-not-dismiss-the-dialog
                dismissHourglass();
            }
        }

    }.execute((Void[]) null);
}

From source file:net.sourceforge.kalimbaradio.androidapp.activity.SelectPlaylistActivity.java

public void validateSubsonicUser() {
    new AsyncTask<Void, Void, String>() {

        @Override//from w  w  w .j  a v  a2  s. c  om
        protected String doInBackground(Void... params) {
            try {

                if (session.getUserDetails().get(SessionManager.KEY_CC) != null
                        && session.getUserDetails().get(SessionManager.KEY_MOBILENUMBER) != null) {

                    // String email_id =session.getAccEmail();
                    String email_id = "";
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpContext localContext = new BasicHttpContext();

                    String URL = Constants.PREFERENCES_KEY_SERVER_ADDRESS
                            + "/rest/getUser.view?u=admin&p=H@rd2Cr@ck&username=" + URLEncoder
                                    .encode(session.getUserDetails().get(SessionManager.KEY_SUBUSER), "UTF-8")
                            + "&v=1.10.2&c=myapp&f=json";

                    HttpGet httpGet = new HttpGet(URL);

                    HttpResponse response = httpClient.execute(httpGet, localContext);
                    HttpEntity entity = response.getEntity();
                    if (entity == null) {
                        throw new RuntimeException("No entity received for URL ");
                    }
                    String json = EntityUtils.toString(entity);
                    String status = "";
                    final JSONObject jsonObj = new JSONObject(json);
                    if (jsonObj != null && jsonObj.has("subsonic-response")) {
                        final JSONObject subresp = (JSONObject) jsonObj.get("subsonic-response");
                        status = subresp.get("status").toString();
                    }

                    URL = Constants.PREFERENCES_REST_SERVER_ADDRESS
                            + "/RESTFull/REST/WebService/UpdateDbUser?cc="
                            + URLEncoder.encode(session.getUserDetails().get(SessionManager.KEY_CC), "UTF-8")
                            + "&mobile_no="
                            + URLEncoder.encode(session.getUserDetails().get(SessionManager.KEY_MOBILENUMBER),
                                    "UTF-8")
                            + "&gcm_regid=" + URLEncoder.encode(regId, "UTF-8") + "&email_id="
                            + URLEncoder.encode(email_id, "UTF-8");
                    System.out.print(URL);
                    //Toast.makeText(getApplicationContext(), "URL: " +URL,Toast.LENGTH_LONG).show();
                    httpGet = new HttpGet(URL);
                    httpClient.execute(httpGet, localContext);

                    if (!status.equalsIgnoreCase("ok")) {
                        httpClient = new DefaultHttpClient();
                        localContext = new BasicHttpContext();

                        URL = Constants.PREFERENCES_REST_SERVER_ADDRESS
                                + "/RESTFull/REST/WebService/AddUser?cc="
                                + URLEncoder
                                        .encode(session.getUserDetails().get(SessionManager.KEY_CC), "UTF-8")
                                + "&mobile_no="
                                + URLEncoder.encode(
                                        session.getUserDetails().get(SessionManager.KEY_MOBILENUMBER), "UTF-8")
                                + "&gcm_regid=" + URLEncoder.encode(regId, "UTF-8") + "&email_id="
                                + URLEncoder.encode(email_id, "UTF-8");
                        System.out.print(URL);
                        //Toast.makeText(getApplicationContext(), "URL: " +URL,Toast.LENGTH_LONG).show();
                        httpGet = new HttpGet(URL);
                        response = httpClient.execute(httpGet, localContext);
                        status = EntityUtils.toString(response.getEntity());
                        if (status.equals("1")) {
                            session.setUserReg();
                        }
                    } else {
                        session.setUserCreation();
                    }

                } else {
                    logout();
                    Intent i = new Intent(getApplicationContext(), loginActivity.class);
                    startActivity(i);
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
                // session.logoutUser();
            }
            return "Works";
        }

        /* @Override
         protected void onPostExecute(String msg) {
        if(session.getUserDetails().get(SessionManager.KEY_CC)!=null && session.getUserDetails().get(SessionManager.KEY_MOBILENUMBER)!=null) {
            Intent i = new Intent(getApplicationContext(), SelectPlaylistActivity.class);
            i.putExtra("regId", regId);
            startActivity(i);
            finish();
        }
        else{
            validateBttn.setEnabled(true);
        }
         }*/

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

From source file:com.meetingninja.csse.MainActivity.java

private void setupRightDrawer() {
    new AsyncTask<Void, Void, Schedule>() {

        @Override/* w  w w.ja  v  a  2  s  . co m*/
        protected Schedule doInBackground(Void... arg0) {
            Schedule sched = new Schedule();
            try {
                sched = UserDatabaseAdapter.getSchedule(SessionManager.getInstance().getUserID());
            } catch (JsonParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return sched;
        }

        @Override
        public void onPostExecute(Schedule result) {
            setupRightDrawer(result);
        }

    }.execute();

}

From source file:ca.rmen.android.networkmonitor.app.log.LogActionsActivity.java

@Override
public void onOkClicked(int actionId, Bundle extras) {
    Log.v(TAG, "onOkClicked, actionId = " + actionId);
    mUserInput = true;/*from  w w w.j  a  v  a  2  s  .c om*/
    // The user confirmed to clear the logs.
    if (actionId == R.id.action_clear) {
        Log.v(TAG, "Clicked ok to clear log");
        DialogFragmentFactory.showProgressDialog(LogActionsActivity.this,
                getString(R.string.progress_dialog_message), ProgressDialog.STYLE_SPINNER, PROGRESS_DIALOG_TAG);
        AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                Log.v(TAG, "clear:doInBackground");
                getContentResolver().delete(NetMonColumns.CONTENT_URI, null, null);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                // Once the DB is deleted, reload the WebView.
                Log.v(TAG, "clear:onPostExecute");
                Toast.makeText(LogActionsActivity.this, R.string.success_logs_clear, Toast.LENGTH_LONG).show();
                setResult(RESULT_OK);
                finish();
            }
        };
        asyncTask.execute();
    }
}