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:$.GooglePlayServicesExtension.java

public void onGSCloudSync(java.lang.Integer id) {
        final Integer fid = id;
        Log.i("yoyo", "onGSCloudSync called with id=" + id);

        AsyncTask<Void, Void, Integer> task = new AsyncTask<Void, Void, Integer>() {
            @Override/*  www .ja  v a  2 s .  com*/
            protected Integer doInBackground(Void... params) {
                // Open the saved game using its name.
                Snapshots.OpenSnapshotResult result = Games.Snapshots.open(mGoogleApiClient, mCurrentSaveName, true)
                        .await();

                int status = result.getStatus().getStatusCode();

                Log.i("yoyo", "get save game data result :" + result.getStatus() + " status=" + status);
                // Check the result of the open operation
                if ((status == GamesStatusCodes.STATUS_OK) || (status == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT)
                        || (status == GamesStatusCodes.STATUS_SNAPSHOT_CONTENTS_UNAVAILABLE)) {
                    Snapshot snapshot = processSnapshotOpenResult(result, 0);

                    //result.getSnapshot();
                    // Read the byte content of the saved game.
                    try {
                        mSaveGameData = snapshot.getSnapshotContents().readFully();

                        String s = new String(mSaveGameData);
                        Log.i("yoyo", "got save game data:" + s);

                        RunnerJNILib.CloudResultData(s.getBytes(), 0/*STATUS_NEW_GAME_DATA*/, fid);
                        return result.getStatus().getStatusCode();
                    } catch (IOException e) {
                        Log.e("yoyo", "Error while reading Snapshot.", e);
                    }
                } else {
                    Log.e("yoyo", "Error while loading: " + result.getStatus().getStatusCode());
                }
                RunnerJNILib.CloudResultData(null, 0/*STATUS_NEW_GAME_DATA*/, fid);
                return result.getStatus().getStatusCode();
            }

            @Override
            protected void onPostExecute(Integer status) {
                // Dismiss progress dialog and reflect the changes in the UI.
                // ...

                Log.i("yoyo", "New cloud save system onPostExecute called with status" + status);

            }
        };

        task.execute();

    }

From source file:cgeo.geocaching.CacheDetailActivity.java

@Override
public boolean onContextItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    // waypoints//from   www . ja  v a 2s . c o  m
    case R.id.menu_waypoint_edit:
        if (selectedWaypoint != null) {
            ensureSaved();
            EditWaypointActivity.startActivityEditWaypoint(this, cache, selectedWaypoint.getId());
            refreshOnResume = true;
        }
        return true;
    case R.id.menu_waypoint_visited:
        if (selectedWaypoint != null) {
            ensureSaved();
            new AsyncTask<Void, Void, Boolean>() {
                @Override
                protected Boolean doInBackground(final Void... params) {
                    selectedWaypoint.setVisited(true);
                    DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
                    return true;
                }

                @Override
                protected void onPostExecute(final Boolean result) {
                    if (result) {
                        notifyDataSetChanged();
                    }
                }
            }.execute();
        }
        return true;
    case R.id.menu_waypoint_copy_coordinates:
        if (selectedWaypoint != null) {
            final Geopoint coordinates = selectedWaypoint.getCoords();
            if (coordinates != null) {
                ClipboardUtils.copyToClipboard(GeopointFormatter.reformatForClipboard(coordinates.toString()));
                showToast(getString(R.string.clipboard_copy_ok));
            }
        }
        return true;
    case R.id.menu_waypoint_clear_coordinates:
        if (selectedWaypoint != null) {
            ensureSaved();
            new ClearCoordinatesCommand(this, cache, selectedWaypoint).execute();
        }
        return true;
    case R.id.menu_waypoint_duplicate:
        ensureSaved();
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(final Void... params) {
                if (cache.duplicateWaypoint(selectedWaypoint) != null) {
                    DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
                    return true;
                }
                return false;
            }

            @Override
            protected void onPostExecute(final Boolean result) {
                if (result) {
                    notifyDataSetChanged();
                }
            }
        }.execute();
        return true;
    case R.id.menu_waypoint_delete:
        ensureSaved();
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(final Void... params) {
                if (cache.deleteWaypoint(selectedWaypoint)) {
                    DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
                    return true;
                }
                return false;
            }

            @Override
            protected void onPostExecute(final Boolean result) {
                if (result) {
                    notifyDataSetChanged();
                }
            }
        }.execute();
        return true;
    case R.id.menu_waypoint_navigate_default:
        if (selectedWaypoint != null) {
            NavigationAppFactory.startDefaultNavigationApplication(1, this, selectedWaypoint);
        }
        return true;
    case R.id.menu_waypoint_navigate:
        if (selectedWaypoint != null) {
            NavigationAppFactory.showNavigationMenu(this, null, selectedWaypoint, null);
        }
        return true;
    case R.id.menu_waypoint_caches_around:
        if (selectedWaypoint != null) {
            final Geopoint coordinates = selectedWaypoint.getCoords();
            if (coordinates != null) {
                CacheListActivity.startActivityCoordinates(this, coordinates, selectedWaypoint.getName());
            }
        }
        return true;
    case R.id.menu_waypoint_reset_cache_coords:
        ensureSaved();
        if (ConnectorFactory.getConnector(cache).supportsOwnCoordinates()) {
            createResetCacheCoordinatesDialog(selectedWaypoint).show();
        } else {
            final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.cache),
                    getString(R.string.waypoint_reset), true);
            final HandlerResetCoordinates handler = new HandlerResetCoordinates(this, progressDialog, false);
            resetCoords(cache, handler, selectedWaypoint, true, false, progressDialog);
        }
        return true;
    case R.id.menu_calendar:
        CalendarAdder.addToCalendar(this, cache);
        return true;
    default:
        break;
    }
    if (imagesList != null && imagesList.onContextItemSelected(item)) {
        return true;
    }
    return onOptionsItemSelected(item);
}

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

private void handleExportPCAP(final Intent data) {
    new AsyncTask<Object, Object, Throwable>() {
        @Override//from   www .  j  av a2s.  c  o  m
        protected Throwable doInBackground(Object... objects) {
            OutputStream out = null;
            FileInputStream in = null;
            try {
                // Stop capture
                ServiceSinkhole.setPcap(false, ActivityLog.this);

                Uri target = data.getData();
                if (data.hasExtra("org.openintents.extra.DIR_PATH"))
                    target = Uri.parse(target + "/netguard.pcap");
                Log.i(TAG, "Export PCAP URI=" + target);
                out = getContentResolver().openOutputStream(target);

                File pcap = new File(getDir("data", MODE_PRIVATE), "netguard.pcap");
                in = new FileInputStream(pcap);

                int len;
                long total = 0;
                byte[] buf = new byte[4096];
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                    total += len;
                }
                Log.i(TAG, "Copied bytes=" + total);

                return null;
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                return ex;
            } finally {
                if (out != null)
                    try {
                        out.close();
                    } catch (IOException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }
                if (in != null)
                    try {
                        in.close();
                    } catch (IOException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

                // Resume capture
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ActivityLog.this);
                if (prefs.getBoolean("pcap", false))
                    ServiceSinkhole.setPcap(true, ActivityLog.this);
            }
        }

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

From source file:export.UploadManager.java

public void loadWorkouts(final HashSet<WorkoutRef> pendingWorkouts, final Callback callback) {
    int cnt = pendingWorkouts.size();
    mSpinner.setTitle("Downloading workouts (" + cnt + ")");
    mSpinner.show();// w  ww .j  ava  2  s .  co  m
    new AsyncTask<String, String, Uploader.Status>() {

        @Override
        protected void onProgressUpdate(String... values) {
            mSpinner.setMessage("Loading " + values[0] + " from " + values[1]);
        }

        @Override
        protected Uploader.Status doInBackground(String... params0) {
            for (WorkoutRef ref : pendingWorkouts) {
                publishProgress(ref.workoutName, ref.uploader);
                Uploader uploader = uploaders.get(ref.uploader);
                //TODO Add back in from runnerup
                // File f = ActivitySerializer.getFile(context, ref.workoutName);
                //File w = f;
                //if (f.exists()) {
                //w = ActivitySerializer.getFile(context, ref.workoutName + ".tmp");
                //}
                try {
                    //  uploader.downloadWorkout(w, ref.workoutKey);
                    //if (w != f) {
                    //  if (compareFiles(w, f) != true) {
                    //    System.err.println("overwriting " + f.getPath() + " with "
                    //          + w.getPath());
                    // TODO dialog
                    //f.delete();
                    //w.renameTo(f);
                    //} else {
                    //  System.err.println("file identical...deleting temporary "
                    //        + w.getPath());
                    //w.delete();
                    //}
                    //}
                } catch (Exception e) {
                    e.printStackTrace();
                    //w.delete();
                }
            }
            return Uploader.Status.OK;
        }

        @Override
        protected void onPostExecute(Uploader.Status result) {
            mSpinner.dismiss();
            if (callback != null) {
                callback.run(null, Uploader.Status.OK);
            }
        }
    }.execute("string");
}

From source file:cn.finalteam.galleryfinal.PhotoEditActivity.java

/**
 * /*from w  w w  .  j a v a  2s  .c o m*/
 */
private void rotatePhoto() {
    if (mPhotoList.size() > 0 && mPhotoList.get(mSelectIndex) != null && !mRotating) {
        final PhotoInfo photoInfo = mPhotoList.get(mSelectIndex);
        final String ext = FilenameUtils.getExtension(photoInfo.getPhotoPath());
        if (StringUtils.isEmpty(ext) || !(ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg")
                || ext.equalsIgnoreCase("jpeg"))) {
            toast(getString(R.string.edit_letoff_photo_format));
            return;
        }
        mRotating = true;
        if (photoInfo != null) {
            final PhotoTempModel photoTempModel = mPhotoTempMap.get(photoInfo.getPhotoId());
            final String path = photoTempModel.getSourcePath();

            File file;
            if (GalleryFinal.getFunctionConfig().isRotateReplaceSource()) { //??
                file = new File(path);
            } else {
                file = new File(mEditPhotoCacheFile, Utils.getFileName(path) + "_rotate." + ext);
            }

            final File rotateFile = file;
            new AsyncTask<Void, Void, Bitmap>() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    mTvEmptyView.setVisibility(View.VISIBLE);
                    mProgressDialog = ProgressDialog.show(PhotoEditActivity.this, "",
                            getString(R.string.waiting), true, false);
                }

                @Override
                protected Bitmap doInBackground(Void... params) {
                    int orientation;
                    if (GalleryFinal.getFunctionConfig().isRotateReplaceSource()) {
                        orientation = 90;
                    } else {
                        orientation = photoTempModel.getOrientation() + 90;
                    }
                    Bitmap bitmap = Utils.rotateBitmap(path, orientation, mScreenWidth, mScreenHeight);
                    if (bitmap != null) {
                        Bitmap.CompressFormat format;
                        if (ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")) {
                            format = Bitmap.CompressFormat.JPEG;
                        } else {
                            format = Bitmap.CompressFormat.PNG;
                        }
                        Utils.saveBitmap(bitmap, format, rotateFile);
                    }
                    return bitmap;
                }

                @Override
                protected void onPostExecute(Bitmap bitmap) {
                    super.onPostExecute(bitmap);
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                        mProgressDialog = null;
                    }
                    if (bitmap != null) {
                        bitmap.recycle();

                        mTvEmptyView.setVisibility(View.GONE);

                        if (!GalleryFinal.getFunctionConfig().isRotateReplaceSource()) {
                            int orientation = photoTempModel.getOrientation() + 90;
                            if (orientation == 360) {
                                orientation = 0;
                            }
                            photoTempModel.setOrientation(orientation);
                        }

                        Message message = mHanlder.obtainMessage();
                        message.what = UPDATE_PATH;
                        message.obj = rotateFile.getAbsolutePath();
                        mHanlder.sendMessage(message);
                    } else {
                        mTvEmptyView.setText(R.string.no_photo);
                    }
                    loadImage(photoInfo);
                    mRotating = false;
                }
            }.execute();
        }
    }
}

From source file:com.shafiq.myfeedle.core.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(Myfeedle.getPackageIntent(this, MyfeedleComments.class).setData(mData));
        } else/*  ww  w.  j  a  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(Myfeedle.getPackageIntent(this, MyfeedleCreatePost.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(Myfeedle
                                                    .getPackageIntent(StatusDialog.this,
                                                            MyfeedleCreatePost.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(Myfeedle.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(Myfeedle.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(Myfeedle.getPackageIntent(this, MyfeedleNotifications.class));
        dialog.cancel();
        finish();
        break;
    case REFRESH:
        if (mAppWidgetId != -1) {
            (Toast.makeText(getApplicationContext(), getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
            startService(Myfeedle.getPackageIntent(this, MyfeedleService.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(Myfeedle.getPackageIntent(StatusDialog.this, MyfeedleService.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(Myfeedle.getPackageIntent(StatusDialog.this, MyfeedleService.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) {
                        MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET, arg0[0],
                                arg0[1]);
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                myfeedleOAuth.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(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mMyfeedleCrypto.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 MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.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(
                        mMyfeedleCrypto.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) {
                        MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET, arg0[0],
                                arg0[1]);
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                myfeedleOAuth.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(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mMyfeedleCrypto.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) {
                        MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, 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 MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                myfeedleOAuth.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(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mMyfeedleCrypto.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) {
                        MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET, arg0[0],
                                arg0[1]);
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                myfeedleOAuth.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(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mMyfeedleCrypto.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 MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                new HttpPost(String.format(CHATTER_URL_ACCESS, 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(
                        mMyfeedleCrypto.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;
    }
}

From source file:at.vcity.androidimsocket.services.IMService.java

public void messageReceived(MessageInfo msg)//String userId, String message)
{
    if (msg != null) {
        Intent i = new Intent(TAKE_MESSAGE);
        localstoragehandler.insert(msg);
        i.putExtra(MessageInfo.MESSAGE, msg);
        sendBroadcast(i);//  w  w w .j  ava 2  s.co m
        FriendInfo activeFriend = FriendController.getActiveFriend();
        if (activeFriend == null)//|| activeFriend.userId.equals(msg.fromUserId) == false) {{
            new AsyncTask<MessageInfo, Void, MessageInfo>() {
                @Override
                protected MessageInfo doInBackground(MessageInfo... m) {
                    while (!FriendController.isFriendListReady()) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                    return m[0];
                }

                @Override
                protected void onPostExecute(MessageInfo msg) {
                    //super.onPostExecute(aVoid);
                    showNotification(msg);//msg.fromUserId, message, msg.type);
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, msg);

    }
    Log.i("TAKE_MESSAGE broadcast sent by im service", "");
}

From source file:com.snappy.CameraCropActivity.java

protected void onPhotoTaken(final String path) {

    String fileName = Uri.parse(path).getLastPathSegment();
    mFilePath = CameraCropActivity.this.getExternalCacheDir() + "/" + fileName;

    if (!path.equals(mFilePath)) {
        copy(new File(path), new File(mFilePath));
    }/*  w w  w  . j av a 2  s .c o  m*/

    new AsyncTask<String, Void, byte[]>() {
        boolean loadingFailed = false;

        @Override
        protected byte[] doInBackground(String... params) {
            try {

                if (!path.equals(mFilePath)) {
                    copy(new File(path), new File(mFilePath));
                }

                if (params == null)
                    return null;

                File f = new File(params[0]);
                ExifInterface exif = new ExifInterface(f.getPath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

                int angle = 0;

                if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                    angle = 90;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                    angle = 180;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                    angle = 270;
                }

                Matrix mat = new Matrix();
                mat.postRotate(angle);

                BitmapFactory.Options optionsMeta = new BitmapFactory.Options();
                optionsMeta.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(f.getAbsolutePath(), optionsMeta);

                BitmapFactory.Options options = new BitmapFactory.Options();

                options.inSampleSize = BitmapManagement.calculateInSampleSize(optionsMeta, 640, 640);
                options.inPurgeable = true;
                options.inInputShareable = true;
                mBitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
                mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), mat,
                        true);
                _scaleBitmap();
                return null;
            } catch (Exception ex) {
                loadingFailed = true;
                finish();
            }

            return null;
        }

        @Override
        protected void onPostExecute(byte[] result) {
            super.onPostExecute(result);

            if (null != mBitmap) {
                mImageView.setImageBitmap(mBitmap);
                mImageView.setScaleType(ScaleType.MATRIX);
                translateMatrix.setTranslate(-(mBitmap.getWidth() - crop_container_size) / 2f,
                        -(mBitmap.getHeight() - crop_container_size) / 2f);
                mImageView.setImageMatrix(translateMatrix);

                matrix = translateMatrix;

            }

        }
    }.execute(mFilePath);

}

From source file:com.pk.wallpapermanager.PkWallpaperManager.java

/**
 * Downloads the wallpaper. Will not thrown an exception. 
 * Check the interface for failed status.
 * <p>/*  ww  w .  j  ava  2s  .  co m*/
 * You can see download progress for the wallpaper passed 
 * through the interface.
 * 
 * @param mWall
 */
public void downloadWallpaperAsync(final Wallpaper mWall, final NotificationManager notification,
        final Builder builder) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                downloadWallpaper(mWall, notification, builder);
            } catch (Exception e) {
                // Loop through all listeners notifying them
                for (WallpaperDownloadListener mListener : mWallpaperDownloadListeners) {
                    mListener.onWallpaperDownloadFailed(mWall);
                }

                e.printStackTrace();
            }

            return null;
        }
    }.execute();
}

From source file:cw.kop.autobackground.sources.SourceInfoFragment.java

@Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {

    if (requestCode == GoogleAccount.GOOGLE_ACCOUNT_SIGN_IN) {
        if (intent != null && responseCode == Activity.RESULT_OK) {
            final String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            AppSettings.setGoogleAccountName(accountName);
            new AsyncTask<Void, Void, Void>() {
                @Override/*from w  ww .  ja v  a2s  . c o  m*/
                protected Void doInBackground(Void... params) {
                    try {
                        String authToken = GoogleAuthUtil.getToken(appContext, accountName,
                                "oauth2:https://picasaweb.google.com/data/");
                        AppSettings.setGoogleAccountToken(authToken);
                        AppSettings.setGoogleAccount(true);
                        new PicasaAlbumTask(-1, true).execute();
                    } catch (IOException transientEx) {
                        return null;
                    } catch (UserRecoverableAuthException e) {
                        e.printStackTrace();
                        startActivityForResult(e.getIntent(), GoogleAccount.GOOGLE_AUTH_CODE);
                        return null;
                    } catch (GoogleAuthException authEx) {
                        return null;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    return null;
                }
            }.execute();
        }
    }
    if (requestCode == GoogleAccount.GOOGLE_AUTH_CODE) {
        if (responseCode == Activity.RESULT_OK) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    try {
                        String authToken = GoogleAuthUtil.getToken(appContext,
                                AppSettings.getGoogleAccountName(),
                                "oauth2:https://picasaweb.google.com/data/");
                        AppSettings.setGoogleAccountToken(authToken);
                        AppSettings.setGoogleAccount(true);
                        new PicasaAlbumTask(-1, true).execute();
                    } catch (IOException transientEx) {
                        return null;
                    } catch (UserRecoverableAuthException e) {
                        return null;
                    } catch (GoogleAuthException authEx) {
                        return null;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    return null;
                }
            }.execute();
        }
    }
}