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.odoo.addons.sale.models.SaleOrder.java

public void confirmSale(final ODataRow quotation, final OnOperationSuccessListener listener) {
    new AsyncTask<Void, Void, Void>() {
        private ProgressDialog dialog;

        @Override//from  w w w . j a  v a  2  s  . com
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(mContext);
            dialog.setTitle(R.string.title_please_wait);
            dialog.setMessage(OResource.string(mContext, R.string.title_working));
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                OArguments args = new OArguments();
                args.add(new JSONArray().put(quotation.getInt("id")));
                args.add(new JSONObject());
                getServerDataHelper().callMethod("action_button_confirm", args);
                OValues values = new OValues();
                values.put("state", "manual");
                values.put("state_title", getStateTitle(values));
                values.put("_is_dirty", "false");
                update(quotation.getInt(OColumn.ROW_ID), values);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.dismiss();
            if (listener != null) {
                listener.OnSuccess();
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
            if (listener != null) {
                listener.OnCancelled();
            }
        }
    }.execute();
}

From source file:ca.rmen.android.scrumchatter.main.MainActivity.java

/**
 * Import the given database file. This will replace the current database.
 *///from  ww w  . j  a  v a2 s .  c o  m
private void importDB(final Uri uri) {
    ScrumChatterDialog.showDialog(this, getString(R.string.import_confirm_title),
            getString(R.string.import_confirm_message, uri.getEncodedPath()), new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
                            private ProgressDialog mProgressDialog;

                            @Override
                            protected void onPreExecute() {
                                mProgressDialog = ProgressDialog.show(MainActivity.this, null,
                                        getString(R.string.progress_dialog_message), true);
                            }

                            @Override
                            protected Boolean doInBackground(Void... params) {
                                try {
                                    Log.v(TAG, "Importing db from " + uri);
                                    DBImport.importDB(MainActivity.this, uri);
                                } catch (Exception e) {
                                    Log.e(TAG, "Error importing db: " + e.getMessage(), e);
                                    return false;
                                }
                                return true;
                            }

                            @Override
                            protected void onPostExecute(Boolean result) {
                                mProgressDialog.cancel();
                                Toast.makeText(MainActivity.this,
                                        result ? R.string.import_result_success : R.string.import_result_failed,
                                        Toast.LENGTH_SHORT).show();
                            }

                        };
                        task.execute();
                    }
                }
            });

}

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

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

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

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

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

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

                    ProgressDialog dialog;

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

                    @Override
                    protected Integer doInBackground(Void... params) {
                        Integer count = 0;
                        BufferedReader br = null;
                        try {
                            br = new BufferedReader(new FileReader(tmp));
                            String line;
                            while ((line = br.readLine()) != null) {
                                int hash = line.indexOf('#');
                                if (hash >= 0)
                                    line = line.substring(0, hash);
                                line = line.trim();

                                if (line.length() > 0) {
                                    String[] words = line.split("\\s+");
                                    if (words.length == 2) {
                                        String blockedDomain = words[1].toLowerCase();
                                        if (blockedDomain.equals("local") || StringUtils.containsAny(
                                                blockedDomain, "localhost", "127.0.0.1", "broadcasthost"))
                                            continue;
                                        DomainFilter domainFilter = new DomainFilter();
                                        domainFilter.setContent(blockedDomain);
                                        domainFilter.setSource(importUrl);
                                        domainFilter.setIsWildcard(false);
                                        db.createDomainFilter(domainFilter);
                                        count++;
                                    } else
                                        Log.i(TAG, "Invalid hosts file line: " + line);
                                }
                            }
                            Log.i(TAG, count + " entries read");
                        } catch (IOException ex) {
                            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        } finally {
                            if (br != null)
                                try {
                                    br.close();
                                } catch (IOException exex) {
                                    Log.e(TAG, exex.toString() + "\n" + Log.getStackTraceString(exex));
                                }
                        }

                        return count;
                    }

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

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

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

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

From source file:com.dealsmessanger.android.DemoActivity.java

public void onClick(final View view) {

    if (view == findViewById(R.id.send)) {
        new AsyncTask<Void, Void, String>() {
            @Override/*from  w ww.j a  v a2 s  .co m*/
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    Bundle data = new Bundle();
                    data.putString("my_message", "Hello World");
                    data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW");
                    String id = Integer.toString(msgId.incrementAndGet());
                    gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
                    msg = "Sent message";
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                }
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                mDisplay.append(msg + "\n");
            }
        }.execute(null, null, null);
    } else if (view == findViewById(R.id.clear)) {
        mDisplay.setText("");
    }
}

From source file:com.twitterdev.rdio.app.RdioApp.java

private void next(final boolean manualPlay) {
    if (player != null) {
        player.stop();//from  ww  w. ja  v  a 2 s  . com
        player.release();
        player = null;
    }

    final Track track = trackQueue.poll();
    if (trackQueue.size() < 3) {
        Log.i(TAG, "Track queue depleted, loading more tracks");
        LoadMoreTracks();
    }

    if (track == null) {
        Log.e(TAG, "Track is null!  Size of queue: " + trackQueue.size());
        return;
    }

    // Load the next track in the background and prep the player (to start buffering)
    // Do this in a bkg thread so it doesn't block the main thread in .prepare()
    AsyncTask<Track, Void, Track> task = new AsyncTask<Track, Void, Track>() {
        @Override
        protected Track doInBackground(Track... params) {
            Track track = params[0];
            final String trackName = track.artistName;
            final String artist = track.trackName;
            try {
                player = rdio.getPlayerForTrack(track.key, null, manualPlay);
                player.prepare();
                player.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        next(false);
                    }
                });
                player.start();
                new getSearch().execute(track.trackName);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView a = (TextView) findViewById(R.id.artist);
                        //a.setText(artist);
                        TextView t = (TextView) findViewById(R.id.track);
                        //t.setText(trackName);
                    }
                });

            } catch (Exception e) {
                Log.e("Test", "Exception " + e);
            }
            return track;
        }

        @Override
        protected void onPostExecute(Track track) {
            updatePlayPause(true);
        }
    };
    task.execute(track);

    // Fetch album art in the background and then update the UI on the main thread
    AsyncTask<Track, Void, Bitmap> artworkTask = new AsyncTask<Track, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Track... params) {
            Track track = params[0];
            try {
                String artworkUrl = track.albumArt.replace("square-200", "square-600");
                Log.i(TAG, "Downloading album art: " + artworkUrl);
                Bitmap bm = null;
                try {
                    URL aURL = new URL(artworkUrl);
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();
                } catch (IOException e) {
                    Log.e(TAG, "Error getting bitmap", e);
                }
                return bm;
            } catch (Exception e) {
                Log.e(TAG, "Error downloading artwork", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap artwork) {
            if (artwork != null) {
                int imageWidth = artwork.getWidth();
                int imageHeight = artwork.getHeight();
                DisplayMetrics dimension = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dimension);
                int newWidth = dimension.widthPixels;

                float scaleFactor = (float) newWidth / (float) imageWidth;
                int newHeight = (int) (imageHeight * scaleFactor);

                artwork = Bitmap.createScaledBitmap(artwork, newWidth, newHeight, true);
                //albumArt.setImageBitmap(bitmap);

                albumArt.setAdjustViewBounds(true);
                albumArt.setImageBitmap(artwork);

            } else
                albumArt.setImageResource(R.drawable.blank_album_art);
        }
    };
    artworkTask.execute(track);

    //Toast.makeText(this, String.format(getResources().getString(R.string.now_playing), track.trackName, track.albumName, track.artistName), Toast.LENGTH_LONG).show();
}

From source file:ca.rmen.android.poetassistant.main.MainActivity.java

/**
 * Clears the search history, and shows a snackbar allowing to undo this clear.
 *///w  w w  .  ja v a 2s .  c  o m
private void clearSearchHistory() {
    new AsyncTask<Void, Void, String[]>() {

        @Override
        protected String[] doInBackground(Void... voids) {
            return mSearch.clearSearchHistory();
        }

        @Override
        protected void onPostExecute(String[] searchHistory) {
            if (searchHistory.length > 0) {
                mClearedHistory = searchHistory;
                showClearHistorySnackbar(searchHistory);
            }
        }
    }.execute();
}

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

@Override
public boolean onContextItemSelected(final MenuItem item) {
    if (item.getItemId() == CLEAR) {
        final ProgressDialog loadingDialog = new ProgressDialog(this);
        final AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

            @Override/*  w w w . j ava2 s .  c o m*/
            protected Void doInBackground(Void... arg0) {
                // clear all notifications
                ContentValues values = new ContentValues();
                values.put(Notifications.CLEARED, 1);
                MyfeedleNotifications.this.getContentResolver().update(
                        Notifications.getContentUri(MyfeedleNotifications.this), values,
                        Notifications._ID + "=?",
                        new String[] { Long.toString(((AdapterContextMenuInfo) item.getMenuInfo()).id) });
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
                MyfeedleNotifications.this.finish();
            }
        };
        loadingDialog.setMessage(getString(R.string.loading));
        loadingDialog.setCancelable(true);
        loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (!asyncTask.isCancelled())
                    asyncTask.cancel(true);
            }
        });
        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();
    }
    return super.onContextItemSelected(item);
    // clear
}

From source file:com.flowzr.activity.FlowzrSyncActivity.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>/*from   www.  j  av  a2s.c o m*/
 * Stores the registration ID and app versionCode in the application's
 * shared preferences.
 */
@SuppressWarnings("unchecked")
private void registerInBackground() {
    AsyncTask execute = new AsyncTask() {

        @Override
        protected Object doInBackground(Object... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                }
                Log.i(TAG, "Registering GCM in background ...");
                regid = gcm.register(FlowzrSyncOptions.GCM_SENDER_ID);
                msg = "Device registered, registration ID=" + regid;

                // You should send the registration ID to your server over HTTP,
                // so it can use GCM/HTTP or CCS to send messages to your app.
                // The request to your server should be authenticated if your app
                // is using accounts.
                sendRegistrationIdToBackend();

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

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

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

}

From source file:com.makerfaireorlando.makerfaireorlando.MainActivity.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>/*from ww  w.  j  a  v a  2 s .c  om*/
 * Stores the registration ID and app versionCode in the application's
 * shared preferences.
 */
private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {

        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                Log.i("regid", regid);
                msg = "Device registered, registration ID=" + regid;

                // You should send the registration ID to your server over HTTP,
                // so it can use GCM/HTTP or CCS to send messages to your app.
                // The request to your server should be authenticated if your app
                // is using accounts.
                sendRegistrationIdToBackend();
                storeRegistrationId(getApplicationContext(), regid);

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

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

        @Override
        protected void onPostExecute(String msg) {
            //mDisplay.append(msg + "\n");
            Log.i(TAG, "message is = " + msg);
        }
    }.execute(null, null, null);
}