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:com.shafiq.myfeedle.core.MyfeedleCreatePost.java

private void setLocation(final long accountId) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {

        int serviceId;

        @Override//from   w  w w .j a v a 2s.com
        protected String doInBackground(Void... none) {
            Cursor account = getContentResolver().query(Accounts.getContentUri(MyfeedleCreatePost.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET },
                    Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
            if (account.moveToFirst()) {
                MyfeedleOAuth myfeedleOAuth;
                serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE));
                switch (serviceId) {
                case TWITTER:
                    // anonymous requests are rate limited to 150 per hour
                    // authenticated requests are rate limited to 350 per hour, so authenticate this!
                    myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET,
                            mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                            mMyfeedleCrypto
                                    .Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
                    return MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong))));
                case FACEBOOK:
                    return MyfeedleHttpClient.httpResponse(mHttpClient,
                            new HttpGet(String.format(FACEBOOK_SEARCH, FACEBOOK_BASE_URL, mLat, mLong,
                                    Saccess_token, mMyfeedleCrypto.Decrypt(
                                            account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                case FOURSQUARE:
                    return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(
                            String.format(FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong, mMyfeedleCrypto
                                    .Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                }
            }
            account.close();
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (response != null) {
                switch (serviceId) {
                case TWITTER:
                    try {
                        JSONArray places = new JSONObject(response).getJSONObject(Sresult)
                                .getJSONArray(Splaces);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sfull_name);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(MyfeedleCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FACEBOOK:
                    try {
                        JSONArray places = new JSONObject(response).getJSONArray(Sdata);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sname);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(MyfeedleCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FOURSQUARE:
                    try {
                        JSONArray groups = new JSONObject(response).getJSONObject(Sresponse)
                                .getJSONArray(Sgroups);
                        for (int g = 0, g2 = groups.length(); g < g2; g++) {
                            JSONObject group = groups.getJSONObject(g);
                            if (group.getString(Sname).equals(SNearby)) {
                                JSONArray places = group.getJSONArray(Sitems);
                                final String placesNames[] = new String[places.length()];
                                final String placesIds[] = new String[places.length()];
                                for (int i = 0, i2 = places.length(); i < i2; i++) {
                                    JSONObject place = places.getJSONObject(i);
                                    placesNames[i] = place.getString(Sname);
                                    placesIds[i] = place.getString(Sid);
                                }
                                mDialog = (new AlertDialog.Builder(MyfeedleCreatePost.this))
                                        .setSingleChoiceItems(placesNames, -1,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        mAccountsLocation.put(accountId, placesIds[which]);
                                                        dialog.dismiss();
                                                    }
                                                })
                                        .setNegativeButton(android.R.string.cancel,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .create();
                                mDialog.show();
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                }
            } else {
                (Toast.makeText(MyfeedleCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG))
                        .show();
            }
        }

    };
    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);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute();
}

From source file:com.grass.caishi.cc.activity.main.MainActivity.java

@SuppressWarnings("unchecked")
public void donBlackground(Map<String, Object> map) {
    new AsyncTask<Map<String, Object>, Void, Void>() {
        @Override//from ww  w .j  a v  a 2s . c  o m
        protected Void doInBackground(Map<String, Object>... params) {
            //
            try {
                new UpLoadImage().download(getApplicationContext(), params[0]);
            } catch (Exception e) {
                //
                e.printStackTrace();
            }
            return null;
        }

    }.execute(map);
}

From source file:com.eugene.fithealthmaingit.UI.SaveSearchAddItemActivityMain.java

private void getFood(final long id) {
    new AsyncTask<String, String, String>() {
        @Override//from  ww  w. ja va 2 s.com
        protected String doInBackground(String... arg0) {
            JSONObject foodGet = mFatSecretGet.getFood(id);
            try {
                if (foodGet != null) {
                    mFoodName = foodGet.getString("food_name");
                    JSONObject servings = foodGet.getJSONObject("servings");
                    Object intervention = servings.get("serving");
                    if (intervention instanceof JSONObject) {
                        arrayOrJson = "object";
                        JSONObject serving = servings.getJSONObject("serving");
                        if (serving.isNull("serving_description")) {
                            mServingDescription = null;
                        } else {
                            mServingDescription = serving.getString("serving_description");
                        }
                        if (serving.isNull("number_of_units")) {
                            mNumberUnits = null;
                        } else {
                            mNumberUnits = serving.getString("number_of_units");
                        }
                        if (serving.isNull("calories")) {
                            mCalories = null;
                        } else {
                            mCalories = serving.getString("calories");
                        }
                        if (serving.isNull("fat")) {
                            mFat = null;
                        } else {
                            mFat = serving.getString("fat");
                        }
                        if (serving.isNull("carbohydrate")) {
                            mCarbohydrates = null;
                        } else {
                            mCarbohydrates = serving.getString("carbohydrate");
                        }
                        if (serving.isNull("protein")) {
                            mProtein = null;
                        } else {
                            mProtein = serving.getString("protein");
                        }
                        if (serving.isNull("saturated_fat")) {
                            mSaturatedFat = null;
                        } else {
                            mSaturatedFat = serving.getString("saturated_fat");
                        }
                        if (serving.isNull("cholesterol")) {
                            mCholesterol = null;
                        } else {
                            mCholesterol = serving.getString("cholesterol");
                        }
                        if (serving.isNull("sodium")) {
                            mSodium = null;
                        } else {
                            mSodium = serving.getString("sodium");
                        }
                        if (serving.isNull("fiber")) {
                            mFiber = null;
                        } else {
                            mFiber = serving.getString("fiber");
                        }
                        if (serving.isNull("sugar")) {
                            mSugar = null;
                        } else {
                            mSugar = serving.getString("sugar");
                        }
                        if (serving.isNull("vitamin_a")) {
                            mVitA = null;
                        } else {
                            mVitA = serving.getString("vitamin_a");
                        }
                        if (serving.isNull("vitamin_c")) {
                            mVitC = null;
                        } else {
                            mVitC = serving.getString("vitamin_c");
                        }
                        if (serving.isNull("calcium")) {
                            mCalcium = null;
                        } else {
                            mCalcium = serving.getString("calcium");
                        }
                        if (serving.isNull("iron")) {
                            mIron = null;
                        } else {
                            mIron = serving.getString("iron");
                        }
                    } else if (intervention instanceof JSONArray) {
                        mItem.clear();
                        JSONArray serving = servings.getJSONArray("serving");
                        for (int i = 0; i < serving.length(); i++) {
                            JSONObject ser = serving.getJSONObject(i);
                            String DifferentServings = ser.getString("serving_description");
                            mItem.add(DifferentServings);
                        }
                        JSONObject newServing = serving.getJSONObject(mLastSpinnerPosition);
                        if (newServing.isNull("serving_description")) {
                            mServingDescription = null;
                        } else {
                            mServingDescription = newServing.getString("serving_description");
                        }
                        if (newServing.isNull("number_of_units")) {
                            mNumberUnits = null;
                        } else {
                            mNumberUnits = newServing.getString("number_of_units");
                        }
                        if (newServing.isNull("calories")) {
                            mCalories = null;
                        } else {
                            mCalories = newServing.getString("calories");
                        }
                        if (newServing.isNull("fat")) {
                            mFat = null;
                        } else {
                            mFat = newServing.getString("fat");
                        }
                        if (newServing.isNull("carbohydrate")) {
                            mCarbohydrates = null;
                        } else {
                            mCarbohydrates = newServing.getString("carbohydrate");
                        }
                        if (newServing.isNull("protein")) {
                            mProtein = null;
                        } else {
                            mProtein = newServing.getString("protein");
                        }
                        if (newServing.isNull("saturated_fat")) {
                            mSaturatedFat = null;
                        } else {
                            mSaturatedFat = newServing.getString("saturated_fat");
                        }
                        if (newServing.isNull("cholesterol")) {
                            mCholesterol = null;
                        } else {
                            mCholesterol = newServing.getString("cholesterol");
                        }
                        if (newServing.isNull("sodium")) {
                            mSodium = null;
                        } else {
                            mSodium = newServing.getString("sodium");
                        }
                        if (newServing.isNull("fiber")) {
                            mFiber = null;
                        } else {
                            mFiber = newServing.getString("fiber");
                        }
                        if (newServing.isNull("sugar")) {
                            mSugar = null;
                        } else {
                            mSugar = newServing.getString("sugar");
                        }
                        if (newServing.isNull("vitamin_a")) {
                            mVitA = null;
                        } else {
                            mVitA = newServing.getString("vitamin_a");
                        }
                        if (newServing.isNull("vitamin_c")) {
                            mVitC = null;
                        } else {
                            mVitC = newServing.getString("vitamin_c");
                        }
                        if (newServing.isNull("calcium")) {
                            mCalcium = null;
                        } else {
                            mCalcium = newServing.getString("calcium");
                        }
                        if (newServing.isNull("iron")) {
                            mIron = null;
                        } else {
                            mIron = newServing.getString("iron");
                        }
                    }
                }
            } catch (JSONException exception) {
                exception.printStackTrace();
                return "Error";
            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.equals("Error")) {

            } else {
                servingAdapter.notifyDataSetChanged();
                setItems();
            }
        }
    }.execute();
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final File pcap_file = new File(getDir("data", MODE_PRIVATE), "netguard.pcap");

    switch (item.getItemId()) {
    case android.R.id.home:
        Log.i(TAG, "Up");
        NavUtils.navigateUpFromSameTask(this);
        return true;

    case R.id.menu_protocol_udp:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("proto_udp", item.isChecked()).apply();
        updateAdapter();/*from  w w w  .  j a  v  a 2  s  .  c  o  m*/
        return true;

    case R.id.menu_protocol_tcp:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("proto_tcp", item.isChecked()).apply();
        updateAdapter();
        return true;

    case R.id.menu_protocol_other:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("proto_other", item.isChecked()).apply();
        updateAdapter();
        return true;

    case R.id.menu_traffic_allowed:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("traffic_allowed", item.isChecked()).apply();
        updateAdapter();
        return true;

    case R.id.menu_traffic_blocked:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("traffic_blocked", item.isChecked()).apply();
        updateAdapter();
        return true;

    case R.id.menu_log_live:
        item.setChecked(!item.isChecked());
        live = item.isChecked();
        if (live) {
            DatabaseHelper.getInstance(this).addLogChangedListener(listener);
            updateAdapter();
        } else
            DatabaseHelper.getInstance(this).removeLogChangedListener(listener);
        return true;

    case R.id.menu_refresh:
        updateAdapter();
        return true;

    case R.id.menu_log_resolve:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("resolve", item.isChecked()).apply();
        adapter.setResolve(item.isChecked());
        adapter.notifyDataSetChanged();
        return true;

    case R.id.menu_log_organization:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("organization", item.isChecked()).apply();
        adapter.setOrganization(item.isChecked());
        adapter.notifyDataSetChanged();
        return true;

    case R.id.menu_pcap_enabled:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("pcap", item.isChecked()).apply();
        ServiceSinkhole.setPcap(item.isChecked(), ActivityLog.this);
        return true;

    case R.id.menu_pcap_export:
        startActivityForResult(getIntentPCAPDocument(), REQUEST_PCAP);
        return true;

    case R.id.menu_log_clear:
        new AsyncTask<Object, Object, Object>() {
            @Override
            protected Object doInBackground(Object... objects) {
                DatabaseHelper.getInstance(ActivityLog.this).clearLog();
                if (prefs.getBoolean("pcap", false)) {
                    ServiceSinkhole.setPcap(false, ActivityLog.this);
                    if (pcap_file.exists() && !pcap_file.delete())
                        Log.w(TAG, "Delete PCAP failed");
                    ServiceSinkhole.setPcap(true, ActivityLog.this);
                } else {
                    if (pcap_file.exists() && !pcap_file.delete())
                        Log.w(TAG, "Delete PCAP failed");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Object result) {
                if (running)
                    updateAdapter();
            }
        }.execute();
        return true;

    case R.id.menu_log_support:
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://github.com/M66B/NetGuard/blob/master/FAQ.md#FAQ27"));
        if (getPackageManager().resolveActivity(intent, 0) != null)
            startActivity(intent);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:eu.intermodalics.tango_ros_streamer.activities.RunningActivity.java

public void onClickItemLoadOccupancyGridDialog(final String occupancyGridName) {
    assert (occupancyGridName != null && !occupancyGridName.isEmpty());
    mLoadOccupancyGridButton.setEnabled(false);
    new AsyncTask<Void, Void, Void>() {
        @Override//from   w  w  w . j  a  v a  2  s  .c  o  m
        protected Void doInBackground(Void... params) {
            mTangoServiceClientNode.callLoadOccupancyGridService(occupancyGridName);
            return null;
        }
    }.execute();
}

From source file:jp.mixi.android.sdk.MixiContainerImpl.java

@Override
public void send(final String endpointPath, final String contentType, final InputStream stream,
        final long length, final CallbackListener listener) {

    AsyncTask<Void, Void, Void> tasc = new AsyncTask<Void, Void, Void>() {
        private Exception e;

        @Override//from   w w  w  .  j a v a  2 s  . c  o m
        protected Void doInBackground(Void... params) {
            try {
                refreshToken();
            } catch (RemoteException e) {
                this.e = e;
            } catch (ApiException e) {
                this.e = e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void res) {
            if (e == null) {
                send(endpointPath, contentType, HttpMethod.POST, stream, length, listener);
            } else {
                Log.v(TAG, "refresh token error");
                listener.onFatal(new ErrorInfo(e));
            }
        }
    };
    tasc.execute(null);
}

From source file:com.clover.android.sdk.examples.InventoryTestActivity.java

private void createObjectsUsingService() {
    if (serviceIsBound && inventoryService != null) {
        new AsyncTask<Void, Void, List<Item>>() {
            @SuppressWarnings("ConstantConditions")
            @Override//from   w ww . j  a  va2s  . com
            protected List<Item> doInBackground(Void... params) {
                List<Item> items = new ArrayList<Item>();
                try {
                    ResultStatus resultStatus = new ResultStatus();

                    // Attempt #1
                    Item newItem = new Item().setName("Test Item #1").setPrice(500L)
                            .setPriceType(PriceType.FIXED).setDefaultTaxRates(true);
                    newItem = inventoryService.createItem(newItem, resultStatus);
                    if (newItem != null) {
                        items.add(newItem);
                    }
                    Log.v(TAG,
                            "Result from createItem() #1 = " + resultStatus + ", item = " + dumpItem(newItem));

                    // Attempt #2, missing data (item name) should be caught by Item() constructor
                    try {
                        Item newItemFailure = new Item().setPrice(500L).setPriceType(PriceType.FIXED)
                                .setDefaultTaxRates(true);
                        newItemFailure = inventoryService.createItem(newItemFailure, resultStatus);
                        if (newItemFailure != null) {
                            items.add(newItemFailure);
                        }
                        Log.v(TAG, "Result from createItem() #2 = " + resultStatus + ", item = "
                                + dumpItem(newItemFailure));
                    } catch (Exception e) {
                        Log.v(TAG, "Result from createItem() #2, where we were missing required field: "
                                + e.getMessage());
                    }

                    // Attempt #3, invalid data (price too low) should be caught by Item() constructor
                    try {
                        Item newItemFailure2 = new Item().setName("Test Item 3").setPrice(-500L)
                                .setPriceType(PriceType.FIXED).setDefaultTaxRates(true);
                        newItemFailure2 = inventoryService.createItem(newItemFailure2, resultStatus);
                        if (newItemFailure2 != null) {
                            items.add(newItemFailure2);
                        }
                        Log.v(TAG, "Result from createItem() #3 = " + resultStatus + ", item = "
                                + dumpItem(newItemFailure2));
                    } catch (Exception e) {
                        Log.v(TAG, "Result from createItem() #3, where we set an invalid value: "
                                + e.getMessage());
                    }

                    // Attempt #4, using server's constructor
                    Item newItemWithId = new Item().setId("XXXXXXXXXXXXX").setName("Test Item 4").setPrice(500L)
                            .setPriceType(PriceType.FIXED).setDefaultTaxRates(true);
                    newItemWithId = inventoryService.createItem(newItemWithId, resultStatus);
                    if (newItemWithId != null) {
                        items.add(newItemWithId);
                    }
                    Log.v(TAG, "Result from createItem() #4 = " + resultStatus + ", item = "
                            + dumpItem(newItemWithId));

                    // Attempt #5, maliciously manipulating data to be invalid
                    String badJson = "{\"name\": \"Way Too Long Name..............................................................................................................................................\",\"price\": 600,\"priceType\": \"FIXED\",\"taxable\": true}";
                    Item newItemBadJson = new Item(badJson);
                    newItemBadJson = inventoryService.createItem(newItemBadJson, resultStatus);
                    if (newItemBadJson != null) {
                        items.add(newItemBadJson);
                    }
                    Log.v(TAG, "Result from createItem() #5 = " + resultStatus + ", item = " + newItemBadJson);
                } catch (Exception e) {
                    Log.e(TAG, "Error calling inventory service", e);
                }
                return items;
            }

            @Override
            protected void onPostExecute(List<Item> results) {
                for (Item result : results) {
                    displayItem(result);
                }
            }
        }.execute();
    }
}

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

/**
 * ???ID???s?.//from  w ww .  java2  s  .c  o m
 * 
 * @param deviceId ?ID
 * @param mediaId ID
 * @param listener 
 */
public static void asynFileReceive(final String deviceId, final String mediaId,
        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();
                HttpGet request = new HttpGet(FILE_URI + "?deviceId=" + deviceId + "&mediaId=" + mediaId);
                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:eu.operando.operandoapp.OperandoProxyStatus.java

private void installCert()
        throws RootCertificateException, GeneralSecurityException, OperatorCreationException, IOException {

    new AsyncTask<Void, Void, Certificate>() {
        Exception error;// w  ww  .j  av  a 2s .  com
        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MainActivity.this, null, "Generating SSL certificate...");
            dialog.setCancelable(false);
        }

        @Override
        protected Certificate doInBackground(Void... params) {
            try {
                Certificate cert = BouncyCastleSslEngineSource
                        .initializeKeyStoreStatic(mainContext.getAuthority());
                return cert;
            } catch (Exception e) {
                error = e;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Certificate certificate) {
            dialog.dismiss();
            if (certificate != null) {
                Intent intent = KeyChain.createInstallIntent();
                try {
                    intent.putExtra(KeyChain.EXTRA_CERTIFICATE, certificate.getEncoded());
                } catch (CertificateEncodingException e) {
                    e.printStackTrace();
                }
                intent.putExtra(KeyChain.EXTRA_NAME, mainContext.getAuthority().commonName());
                startActivityForResult(intent, 1);
            } else {
                Toast.makeText(MainActivity.this, "Failed to load certificates, exiting: " + error.getMessage(),
                        Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }.execute();

}

From source file:com.piusvelte.sonet.StatusDialog.java

@Override
public void onClick(final DialogInterface dialog, int which) {
    switch (which) {
    case COMMENT:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST) {
                if (mSid != null)
                    startActivity(new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse(String.format(PINTEREST_PIN, mSid))));
                else
                    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            } else
                startActivity(Sonet.getPackageIntent(this, SonetComments.class).setData(mData));
        } else//from w  w w. ja v a 2  s.  c o  m
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        dialog.cancel();
        finish();
        break;
    case POST:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            else
                startActivity(Sonet.getPackageIntent(this, SonetCreatePost.class).setData(Uri
                        .withAppendedPath(Accounts.getContentUri(StatusDialog.this), Long.toString(mAccount))));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // no account, dialog to select one
                        // don't limit accounts to the widget
                        Cursor c = StatusDialog.this.getContentResolver().query(
                                Accounts.getContentUri(StatusDialog.this),
                                new String[] { Accounts._ID, ACCOUNTS_QUERY }, null, null, null);
                        if (c.moveToFirst()) {
                            int iid = c.getColumnIndex(Accounts._ID),
                                    iusername = c.getColumnIndex(Accounts.USERNAME), i = 0;
                            final long[] accountIndexes = new long[c.getCount()];
                            final String[] accounts = new String[c.getCount()];
                            while (!c.isAfterLast()) {
                                long id = c.getLong(iid);
                                accountIndexes[i] = id;
                                accounts[i++] = c.getString(iusername);
                                c.moveToNext();
                            }
                            arg0.cancel();
                            mDialog = (new AlertDialog.Builder(StatusDialog.this)).setTitle(R.string.accounts)
                                    .setSingleChoiceItems(accounts, -1, new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int which) {
                                            startActivity(Sonet
                                                    .getPackageIntent(StatusDialog.this, SonetCreatePost.class)
                                                    .setData(Uri.withAppendedPath(
                                                            Accounts.getContentUri(StatusDialog.this),
                                                            Long.toString(accountIndexes[which]))));
                                            arg0.cancel();
                                        }
                                    }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                                        @Override
                                        public void onCancel(DialogInterface arg0) {
                                            dialog.cancel();
                                        }
                                    }).create();
                            mDialog.show();
                        } else {
                            (Toast.makeText(StatusDialog.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                            dialog.cancel();
                        }
                        c.close();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case SETTINGS:
        if (mAppWidgetId != -1) {
            startActivity(Sonet.getPackageIntent(this, ManageAccounts.class)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        startActivity(Sonet.getPackageIntent(StatusDialog.this, ManageAccounts.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetIds[arg1]));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case NOTIFICATIONS:
        startActivity(Sonet.getPackageIntent(this, SonetNotifications.class));
        dialog.cancel();
        finish();
        break;
    case REFRESH:
        if (mAppWidgetId != -1) {
            (Toast.makeText(getApplicationContext(), getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
            startService(Sonet.getPackageIntent(this, SonetService.class).setAction(ACTION_REFRESH)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId }));
            dialog.cancel();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Sonet.getPackageIntent(StatusDialog.this, SonetService.class)
                                .setAction(ACTION_REFRESH).putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
                                        new int[] { mAppWidgetIds[arg1] }));
                        arg0.cancel();
                        finish();
                    }
                }).setPositiveButton(R.string.refreshallwidgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int which) {
                        // refresh all
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Sonet.getPackageIntent(StatusDialog.this, SonetService.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, mAppWidgetIds));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                dialog.cancel();
                finish();
            }
        }
        break;
    case PROFILE:
        Cursor account;
        final AsyncTask<String, Void, String> asyncTask;
        // get the resources
        switch (mService) {
        case TWITTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY,
                                BuildConfig.TWITTER_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri
                                        .parse(String.format(TWITTER_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        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);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FACEBOOK:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                new HttpGet(String.format(FACEBOOK_USER, FACEBOOK_BASE_URL, mEsid,
                                        Saccess_token, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getString("link"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        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);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        case MYSPACE:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY,
                                BuildConfig.MYSPACE_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(MYSPACE_USER, MYSPACE_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getJSONObject("person")
                                                .getString("profileUrl"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        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);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FOURSQUARE:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(FOURSQUARE_URL_PROFILE, mEsid))));
            finish();
            break;
        case LINKEDIN:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY,
                                BuildConfig.LINKEDIN_SECRET, arg0[0], arg0[1]);
                        HttpGet httpGet = new HttpGet(String.format(LINKEDIN_URL_USER, mEsid));
                        for (String[] header : LINKEDIN_HEADERS)
                            httpGet.setHeader(header[0], header[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(httpGet));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        (new JSONObject(response)).getJSONObject("siteStandardProfileRequest")
                                                .getString("url").replaceAll("\\\\", ""))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        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);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case IDENTICA:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY,
                                BuildConfig.IDENTICA_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        String.format(IDENTICA_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        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);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case GOOGLEPLUS:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(GOOGLEPLUS_PROFILE, mEsid))));
            finish();
            break;
        case PINTEREST:
            if (mEsid != null)
                startActivity(new Intent(Intent.ACTION_VIEW)
                        .setData(Uri.parse(String.format(PINTEREST_PROFILE, mEsid))));
            else
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            finish();
            break;
        case CHATTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        // need to get an instance
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()), new HttpPost(
                                        String.format(CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.has("instance_url")) {
                                    startActivity(new Intent(Intent.ACTION_VIEW)
                                            .setData(Uri.parse(jobj.getString("instance_url") + "/" + mEsid)));
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        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);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        }
        break;
    default:
        if ((itemsData != null) && (which < itemsData.length) && (itemsData[which] != null))
            // open link
            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(itemsData[which])));
        else
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        finish();
        break;
    }
}