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.microsoft.onedrive.apiexplorer.ItemFragment.java

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    final BaseApplication application = (BaseApplication) getActivity().getApplication();
    final IOneDriveClient oneDriveClient = application.getOneDriveClient();

    if (requestCode == REQUEST_CODE_SIMPLE_UPLOAD && data != null && data.getData() != null
            && data.getData().getScheme().equalsIgnoreCase(SCHEME_CONTENT)) {

        final ProgressDialog dialog = new ProgressDialog(getActivity());
        dialog.setTitle(R.string.upload_in_progress_title);
        dialog.setMessage(getString(R.string.upload_in_progress_message));
        dialog.setIndeterminate(false);// w w w. j  ava  2  s  .co m
        dialog.setCancelable(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgressNumberFormat(getString(R.string.upload_in_progress_number_format));
        dialog.show();
        final AsyncTask<Void, Void, Void> uploadFile = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(final Void... params) {
                try {
                    final ContentResolver contentResolver = getActivity().getContentResolver();
                    final ContentProviderClient contentProvider = contentResolver
                            .acquireContentProviderClient(data.getData());
                    final byte[] fileInMemory = FileContent.getFileBytes(contentProvider, data.getData());
                    contentProvider.release();

                    // Fix up the file name (needed for camera roll photos, etc)
                    final String filename = FileContent.getValidFileName(contentResolver, data.getData());
                    final Option option = new QueryOption("@name.conflictBehavior", "fail");
                    oneDriveClient.getDrive().getItems(mItemId).getChildren().byId(filename).getContent()
                            .buildRequest(Collections.singletonList(option))
                            .put(fileInMemory, new IProgressCallback<Item>() {
                                @Override
                                public void success(final Item item) {
                                    dialog.dismiss();
                                    Toast.makeText(getActivity(),
                                            application.getString(R.string.upload_complete, item.name),
                                            Toast.LENGTH_LONG).show();
                                    refresh();
                                }

                                @Override
                                public void failure(final ClientException error) {
                                    dialog.dismiss();
                                    if (error.isError(OneDriveErrorCodes.NameAlreadyExists)) {
                                        Toast.makeText(getActivity(), R.string.upload_failed_name_conflict,
                                                Toast.LENGTH_LONG).show();
                                    } else {
                                        Toast.makeText(getActivity(),
                                                application.getString(R.string.upload_failed, filename),
                                                Toast.LENGTH_LONG).show();
                                    }
                                }

                                @Override
                                public void progress(final long current, final long max) {
                                    dialog.setProgress((int) current);
                                    dialog.setMax((int) max);
                                }
                            });
                } catch (final Exception e) {
                    Log.e(getClass().getSimpleName(), e.getMessage());
                    Log.e(getClass().getSimpleName(), e.toString());
                }
                return null;
            }
        };
        uploadFile.execute();
    }
}

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

@Override
public void onClick(View v) {
    if (v == mSend) {
        if (!mAccountsService.isEmpty()) {
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
                @Override/* w ww  . j a v  a2  s.  c  o  m*/
                protected Void doInBackground(Void... arg0) {
                    Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator();
                    while (entrySet.hasNext()) {
                        Map.Entry<Long, Integer> entry = entrySet.next();
                        final long accountId = entry.getKey();
                        final int service = entry.getValue();
                        final String placeId = mAccountsLocation.get(accountId);
                        // post or comment!
                        Cursor account = getContentResolver().query(
                                Accounts.getContentUri(MyfeedleCreatePost.this),
                                new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET },
                                Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
                        if (account.moveToFirst()) {
                            final String serviceName = Myfeedle.getServiceName(getResources(), service);
                            publishProgress(serviceName);
                            String message;
                            MyfeedleOAuth myfeedleOAuth;
                            HttpPost httpPost;
                            String response = null;
                            switch (service) {
                            case TWITTER:
                                myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                message = mMessage.getText().toString();
                                while (message.length() > 0) {
                                    final String send;
                                    if (message.length() > 140) {
                                        // need to break on a word
                                        int end = 0;
                                        int nextSpace = 0;
                                        for (int i = 0, i2 = message.length(); i < i2; i++) {
                                            end = nextSpace;
                                            if (message.substring(i, i + 1).equals(" ")) {
                                                nextSpace = i;
                                            }
                                        }
                                        // in case there are no spaces, just break on 140
                                        if (end == 0) {
                                            end = 140;
                                        }
                                        send = message.substring(0, end);
                                        message = message.substring(end + 1);
                                    } else {
                                        send = message;
                                        message = "";
                                    }
                                    httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL));
                                    // resolve Error 417 Expectation by Twitter
                                    httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                            false);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                                myfeedleOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case FACEBOOK:
                                // handle tags
                                StringBuilder tags = null;
                                if (mAccountsTags.containsKey(accountId)) {
                                    String[] accountTags = mAccountsTags.get(accountId);
                                    if ((accountTags != null) && (accountTags.length > 0)) {
                                        tags = new StringBuilder();
                                        tags.append("[");
                                        String tag_format;
                                        if (mPhotoPath != null)
                                            tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}";
                                        else
                                            tag_format = "%s";
                                        for (int i = 0, l = accountTags.length; i < l; i++) {
                                            if (i > 0)
                                                tags.append(",");
                                            tags.append(String.format(tag_format, accountTags[i]));
                                        }
                                        tags.append("]");
                                    }
                                }
                                if (mPhotoPath != null) {
                                    // upload photo
                                    // uploading a photo takes a long time, have the service handle it
                                    Intent i = Myfeedle.getPackageIntent(
                                            MyfeedleCreatePost.this.getApplicationContext(),
                                            PhotoUploadService.class);
                                    i.setAction(Myfeedle.ACTION_UPLOAD);
                                    i.putExtra(Accounts.TOKEN,
                                            account.getString(account.getColumnIndex(Accounts.TOKEN)));
                                    i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath);
                                    i.putExtra(Statuses.MESSAGE, mMessage.getText().toString());
                                    i.putExtra(Splace, placeId);
                                    if (tags != null)
                                        i.putExtra(Stags, tags.toString());
                                    startService(i);
                                    publishProgress(serviceName + " photo");
                                } else {
                                    // regular post
                                    httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL,
                                            Saccess_token, mMyfeedleCrypto.Decrypt(account
                                                    .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                                    if (placeId != null)
                                        params.add(new BasicNameValuePair(Splace, placeId));
                                    if (tags != null)
                                        params.add(new BasicNameValuePair(Stags, tags.toString()));
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case MYSPACE:
                                myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    HttpPut httpPut = new HttpPut(
                                            String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL));
                                    httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY,
                                            mMessage.getText().toString())));
                                    response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                            myfeedleOAuth.getSignedRequest(httpPut));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                // warn users about myspace permissions
                                if (response != null) {
                                    publishProgress(serviceName, getString(R.string.success));
                                } else {
                                    publishProgress(serviceName, getString(R.string.failure) + " "
                                            + getString(R.string.myspace_permissions_message));
                                }
                                break;
                            case FOURSQUARE:
                                try {
                                    message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                                    if (placeId != null) {
                                        if (message != null) {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN,
                                                    FOURSQUARE_BASE_URL, placeId, message, mLat, mLong,
                                                    mMyfeedleCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        } else {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT,
                                                    FOURSQUARE_BASE_URL, placeId, mLat, mLong,
                                                    mMyfeedleCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        }
                                    } else {
                                        httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE,
                                                FOURSQUARE_BASE_URL, message, mMyfeedleCrypto.Decrypt(account
                                                        .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    }
                                    response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case LINKEDIN:
                                myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL));
                                    httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_BODY, "",
                                            mMessage.getText().toString())));
                                    httpPost.addHeader(new BasicHeader("Content-Type", "application/xml"));
                                    response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                            myfeedleOAuth.getSignedRequest(httpPost));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case IDENTICA:
                                myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                message = mMessage.getText().toString();
                                while (message.length() > 0) {
                                    final String send;
                                    if (message.length() > 140) {
                                        // need to break on a word
                                        int end = 0;
                                        int nextSpace = 0;
                                        for (int i = 0, i2 = message.length(); i < i2; i++) {
                                            end = nextSpace;
                                            if (message.substring(i, i + 1).equals(" ")) {
                                                nextSpace = i;
                                            }
                                        }
                                        // in case there are no spaces, just break on 140
                                        if (end == 0) {
                                            end = 140;
                                        }
                                        send = message.substring(0, end);
                                        message = message.substring(end + 1);
                                    } else {
                                        send = message;
                                        message = "";
                                    }
                                    httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL));
                                    // resolve Error 417 Expectation by Twitter
                                    httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                            false);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                                myfeedleOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case CHATTER:
                                // need to get an updated access_token
                                response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpPost(
                                        String.format(CHATTER_URL_ACCESS, CHATTER_KEY, mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                                if (response != null) {
                                    try {
                                        JSONObject jobj = new JSONObject(response);
                                        if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                            httpPost = new HttpPost(String.format(CHATTER_URL_POST,
                                                    jobj.getString("instance_url"),
                                                    Uri.encode(mMessage.getText().toString())));
                                            httpPost.setHeader("Authorization",
                                                    "OAuth " + jobj.getString(Saccess_token));
                                            response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, serviceName + ":" + e.toString());
                                        Log.e(TAG, response);
                                    }
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            }
                        }
                        account.close();
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    if (params.length == 1) {
                        loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                    } else {
                        (Toast.makeText(MyfeedleCreatePost.this, params[0] + " " + params[1],
                                Toast.LENGTH_LONG)).show();
                    }
                }

                @Override
                protected void onPostExecute(Void result) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    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();
                        }
                    });
            loadingDialog.show();
            asyncTask.execute();
        } else
            (Toast.makeText(MyfeedleCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show();
    }
}

From source file:export.UploadManager.java

private void doUploadMulti(final Uploader uploader, final long id) {
    final ProgressDialog copySpinner = mSpinner;
    final SQLiteDatabase copyDB = mDBHelper.getWritableDatabase();

    copySpinner.setMessage(Long.toString(1 + uploadActivities.size()) + " remaining");
    new AsyncTask<Uploader, String, Uploader.Status>() {

        @Override/*from   www .  ja v a  2 s .c o  m*/
        protected Uploader.Status doInBackground(Uploader... params) {
            try {
                return uploader.upload(copyDB, id);
            } catch (Exception ex) {
                ex.printStackTrace();
                return Uploader.Status.ERROR;
            }
        }

        @Override
        protected void onPostExecute(Uploader.Status result) {
            switch (result) {
            case CANCEL:
            case ERROR:
            case INCORRECT_USAGE:
            case SKIP:
                break;
            case OK:
                uploadOK(uploader, copySpinner, copyDB, id);
                break;
            case NEED_AUTH:
                handleAuth(new Callback() {
                    @Override
                    public void run(String uploaderName, export.Uploader.Status status) {
                        switch (status) {
                        case CANCEL:
                        case SKIP:
                        case ERROR:
                        case INCORRECT_USAGE:
                        case NEED_AUTH: // should be handled inside
                                        // connect "loop"
                            uploadActivities.clear();
                            uploadNextActivity(uploader);
                            break;
                        case OK:
                            doUploadMulti(uploader, id);
                            break;
                        }
                    }
                }, uploader, result.authMethod);

                break;
            }
            uploadNextActivity(uploader);
        }
    }.execute(uploader);
}

From source file:edu.mum.ml.group7.guessasketch.android.EasyPaint.java

private void sendPost(final File file, final ApiCallType apiCallType, final String label) {

    AsyncTask<File, Void, String> task = new AsyncTask<File, Void, String>() {
        private boolean success_call = false;

        @Override/* ww w.  j  a  v  a 2  s  .c om*/
        protected void onCancelled() {
            super.onCancelled();
            if (apiCallType != ApiCallType.GUESS_IMAGE) {
                resetPredictionsView(predictions, true);
            }
            if (success_call && apiCallType == ApiCallType.GUESS_IMAGE) {
                saveButton.setVisibility(View.VISIBLE);
            }
            loader.setVisibility(View.INVISIBLE);

            file.delete();

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (apiCallType != ApiCallType.GUESS_IMAGE) {
                resetPredictionsView(predictions, true);
            }
            if (success_call && apiCallType == ApiCallType.GUESS_IMAGE) {
                saveButton.setVisibility(View.VISIBLE);
            }
            loader.setVisibility(View.INVISIBLE);

            file.delete();

        }

        @Override
        protected String doInBackground(File... files) {
            String responseString = "";

            try {
                String endpointURL = Constants.guessAPI;
                String callType = "";
                switch (apiCallType) {
                case NEGATIVE_FEEDBACK:
                    callType = "neg";
                    break;
                case POSITIVE_FEEDBACK:
                    callType = "pos";
                    break;
                case GUESS_IMAGE:
                default:
                    callType = "guess";

                }
                Log.e("sendPost", "Trying API " + endpointURL);
                MultipartUtility multipart = new MultipartUtility(endpointURL, "utf8");

                // label is only needed if we're sending pos/neg feedback
                if (!callType.equals("guess")) {
                    multipart.addFormField("label", label);
                }

                multipart.addFormField("call_type", callType);
                multipart.addFilePart("file", file);

                String TAG = "upload";

                List<String> response = multipart.finish();
                Log.e(TAG, "SERVER REPLIED:");
                for (String line : response) {
                    Log.e(TAG, "Upload Files Response:::" + line);
                    // get your server response here.
                    responseString += line;
                }
                success_call = true;
            } catch (final IOException e) {
                e.printStackTrace();
                Log.e("sendPost", e.getMessage());
                EasyPaint.this.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

                success_call = false;
            }

            try {
                JSONObject jObject = new JSONObject(responseString);
                if (apiCallType == ApiCallType.GUESS_IMAGE) {
                    refreshLabels(jObject);
                } else {
                    EasyPaint.this.runOnUiThread(new Runnable() {
                        public void run() {
                            saveButton.setVisibility(View.INVISIBLE);
                            Toast.makeText(getApplicationContext(), R.string.feedback_submitted,
                                    Toast.LENGTH_LONG).show();

                        }
                    });
                }

            } catch (final JSONException e) {
                e.printStackTrace();
                Log.e("sendPost", e.getMessage());
                EasyPaint.this.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
                success_call = false;
            }

            return responseString;

        }
    };

    task.execute(file);

}

From source file:com.msted.lensrocket.LensRocketService.java

/***************************************************************/

@SuppressWarnings({ "unchecked", "rawtypes" })
public void registerForPush() {
    mGcm = GoogleCloudMessaging.getInstance(mContext);
    mHub = new NotificationHub(Constants.NOTIFICATIN_HUB_NAME, Constants.NOTIFICATION_HUB_CONNECTION_STRING,
            mContext);//from  www.j  a  v a  2 s  .  c om
    new AsyncTask() {
        @Override
        protected Object doInBackground(Object... params) {
            try {
                LensRocketLogger.i(TAG, "Registering for push notifications");
                String regId = mGcm.register(Constants.SENDER_ID);
                LensRocketLogger.i(TAG, "Registration ID: " + regId);
                if (!regId.equals(mRegistrationId)) {
                    LensRocketLogger.i(TAG, "Registerin with NotHubs");
                    mRegistrationId = regId;
                    SharedPreferences settings = mContext.getSharedPreferences("UserData", 0);
                    SharedPreferences.Editor preferencesEditor = settings.edit();
                    preferencesEditor.putString("registrationId", mRegistrationId);
                    preferencesEditor.commit();

                    mHub.registerTemplate(mRegistrationId, "messageTemplate",
                            "{\"data\":{\"message\":\"$(message)\"}, \"collapse_key\":\"$(collapse_key)\"}",
                            mClient.getCurrentUser().getUserId(), "AllUsers", "AndroidUser");
                }
            } catch (Exception e) {
                LensRocketLogger.e(TAG, "Unable to register for push notifications: " + e.getMessage());
                return e;
            }
            return null;
        }
    }.execute(null, null, null);
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

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

        @Override//  w  ww  . j  ava  2 s. c  om
        protected String doInBackground(Void... params) {
            try {

                String songTitle = currentPlaying.getSong().getTitle();
                String musicType = isAd() ? "A" : "M";
                SessionManager session = new SessionManager(getApplicationContext());
                String cc = session.getUserDetails().get(SessionManager.KEY_CC);
                String mobileNo = session.getUserDetails().get(SessionManager.KEY_MOBILENUMBER);
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();

                // String URL = Constants.PREFERENCES_KEY_SERVER_ADDRESS + "/rest/createUser.view?u=admin&p=kalimba&username=" + URLEncoder.encode(session.getUserDetails().get(SessionManager.KEY_SUBUSER), "UTF-8") + "&password=" + URLEncoder.encode(Constants.PREFERENCES_KEY_SERVER_USER_PASSWORD, "UTF-8") + "&email=" + URLEncoder.encode(session.getUserDetails().get(SessionManager.KEY_SUBUSER) + "@kalimbaradio.com", "UTF-8") + "&v=1.10.2&c=myapp&f=json";
                String URL = Constants.PREFERENCES_REST_SERVER_ADDRESS
                        + "/RESTFull/REST/Report/AddTransaction?cc=" + URLEncoder.encode(cc, "UTF-8")
                        + "&mobile_no=" + URLEncoder.encode(mobileNo, "UTF-8") + "&song_name="
                        + URLEncoder.encode(songTitle, "UTF-8") + "&music_type="
                        + URLEncoder.encode(musicType, "UTF-8");

                HttpGet httpGet = new HttpGet(URL);

                HttpResponse response = httpClient.execute(httpGet, localContext);

                //  Toast.makeText(getApplicationContext(), response.getStatusLine().getStatusCode(), Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return "Works";
        }

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

From source file:com.example.pyrkesa.shwc.MainActivity.java

private void dismissNotification() {
    if (mGoogleApiClient.isConnected()) {
        new AsyncTask<Void, Void, Void>() {
            @Override//from  w  w  w. j  a va 2  s . c o  m
            protected Void doInBackground(Void... params) {
                NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient)
                        .await();
                for (Node node : nodes.getNodes()) {
                    MessageApi.SendMessageResult result = Wearable.MessageApi
                            .sendMessage(mGoogleApiClient, node.getId(), PATH_DISMISS, null).await();
                    if (!result.getStatus().isSuccess()) {
                        Log.e(TAG_DISMISS, "ERROR: failed to send Message: " + result.getStatus());
                    }
                }
                return null;
            }
        }.execute();
    }
}

From source file:org.deviceconnect.android.manager.setting.ReqResDebugActivity.java

/**
 * Http?./*w  w w . j av a  2s .c  o m*/
 * @param request 
 * @param listener Http????
 */
private void executeHttpRequest(final HttpUriRequest request, final HttpListener listener) {
    if (!showProgressDialog()) {
        return;
    }
    AsyncTask<HttpUriRequest, HttpUriRequest, String> task = new AsyncTask<HttpUriRequest, HttpUriRequest, String>() {
        @Override
        protected String doInBackground(final HttpUriRequest... params) {
            if (params == null || params.length < 1) {
                return "Illegal Parameter.";
            }

            HttpUriRequest request = params[0];
            DefaultHttpClient client = new DefaultHttpClient();
            try {
                HttpResponse response = client.execute(request);
                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    try {
                        return EntityUtils.toString(response.getEntity(), "UTF-8");
                    } catch (ParseException e) {
                        return e.getMessage();
                    } catch (IOException e) {
                        return e.getMessage();
                    }
                case HttpStatus.SC_NOT_FOUND:
                    return "Not found. 404";
                default:
                    return "Http connect error.";
                }
            } catch (ClientProtocolException e) {
                return e.getMessage();
            } catch (IOException e) {
                return e.getMessage();
            } finally {
                client.getConnectionManager().shutdown();
            }
        }

        @Override
        protected void onPostExecute(final String response) {
            super.onPostExecute(response);

            hideProgressDialog();

            if (response == null) {
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.append("Request:\n");
            sb.append(request.getMethod() + " " + request.getURI() + "\n");
            mListAdapter.add(sb.toString());
            mListAdapter.add("Response:\n" + response);
            mListAdapter.notifyDataSetChanged();
            if (listener != null) {
                listener.onReceivedResponse(response);
            }
        }
    };
    task.execute(request);
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

private void registerInBackground(final String userId) {
    new AsyncTask<Void, Void, String>() {
        @Override//from   w  w w  .ja  v a  2  s  . c  om
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(appContext);
                }
                deviceToken = gcm.register(gcmSenderId);
                gcm.close();
                logger.info(
                        "MFPPush:registerInBackground() - Successfully registered with GCM. Returned deviceToken is: "
                                + deviceToken);
                computeRegId();
                if (MFPPushUtils.validateString(userId)) {
                    registerWithUserId(userId);
                } else {
                    register();
                }
            } catch (IOException ex) {
                msg = ex.getMessage();
                //Failed to register at GCM Server.
                logger.error("MFPPush:registerInBackground() - Failed to register at GCM Server. Exception is: "
                        + ex.getMessage());
                registerResponseListener.onFailure(new MFPPushException(msg));
            }
            return msg;
        }
    }.execute(null, null, null);
}

From source file:com.dngames.mobilewebcam.PhotoSettings.java

public void DownloadImprintBitmap() {
    // get from URL
    Handler h = new Handler(mContext.getMainLooper());
    h.post(new Runnable() {
        @Override/*from   ww  w  .j  a va2  s .  c  o m*/
        public void run() {
            try {
                new AsyncTask<String, Void, Bitmap>() {
                    @Override
                    protected Bitmap doInBackground(String... params) {
                        try {
                            URL url = new URL(mImprintPictureURL);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                            InputStream is = connection.getInputStream();
                            return BitmapFactory.decodeStream(is);
                        } catch (MalformedURLException e) {
                            if (e.getMessage() != null)
                                MobileWebCam.LogE("Imprint picture URL error: " + e.getMessage());
                            else
                                MobileWebCam.LogE("Imprint picture URL invalid!");
                            e.printStackTrace();
                        } catch (IOException e) {
                            if (e.getMessage() != null)
                                MobileWebCam.LogE(e.getMessage());
                            e.printStackTrace();
                        }

                        return null;
                    }

                    @Override
                    protected void onPostExecute(Bitmap result) {
                        if (result == null && !mNoToasts)
                            Toast.makeText(mContext, "Imprint picture download failed!", Toast.LENGTH_SHORT)
                                    .show();

                        synchronized (PhotoSettings.gImprintBitmapLock) {
                            PhotoSettings.gImprintBitmap = result;
                        }
                    }
                }.execute().get();
            } catch (Exception e) {
                if (e.getMessage() != null)
                    MobileWebCam.LogE(e.getMessage());
                e.printStackTrace();
            }
        }
    });
}