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.foundstone.certinstaller.CertInstallerActivity.java

/**
 * Build a connection using the custom Trust Manager and Socket Factory to
 * grab the certificates./*w w  w . j  a  v  a 2  s  .c o m*/
 * 
 * @param urlString
 * @param proxyIP
 * @param proxyPort
 */
public void grabCerts(final String urlString, final String proxyIP, final String proxyPort) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry
                    .register(new Scheme("https", new EasySSLSocketFactory(CertInstallerActivity.this), 443));

            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
            httpParams.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
            httpParams.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
            Log.d(TAG, proxyIP);
            Log.d(TAG, proxyPort);
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyIP, Integer.parseInt(proxyPort)));
            HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

            ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

            DefaultHttpClient defaultClient = new DefaultHttpClient(cm, httpParams);
            HttpGet httpget = new HttpGet();
            try {
                httpget.setURI(new URI("https://" + urlString));
                Log.d(TAG, urlString);

                HttpResponse httpResponse = defaultClient.execute(httpget);
                InputStream in = httpResponse.getEntity().getContent();
                // Once this connection is made the certs are grabbed
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

    }.execute();
}

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

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

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

                if (session.getUserDetails().get(SessionManager.KEY_CC) != null
                        && session.getUserDetails().get(SessionManager.KEY_MOBILENUMBER) != null) {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpContext localContext = new BasicHttpContext();

                    httpClient = new DefaultHttpClient();
                    localContext = new BasicHttpContext();

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

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

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

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

From source file:edu.cens.loci.ui.PlaceViewActivity.java

public void onQueryComplete(int token, Object cookie, final Cursor cursor) {
    final ArrayList<Entity> oldEntities = mEntities;
    (new AsyncTask<Void, Void, ArrayList<Entity>>() {
        @Override//w  w w.j  a  v  a2s  . c o  m
        protected ArrayList<Entity> doInBackground(Void... params) {
            ArrayList<Entity> newEntities = new ArrayList<Entity>(cursor.getCount());
            EntityIterator iterator = Places.newEntityIterator(cursor);
            try {
                while (iterator.hasNext()) {
                    Entity entity = iterator.next();
                    newEntities.add(entity);
                }
            } finally {
                iterator.close();
            }
            return newEntities;
        }

        @Override
        protected void onPostExecute(ArrayList<Entity> newEntities) {
            if (newEntities == null) {
                // There was an error loading.
                return;
            }
            synchronized (PlaceViewActivity.this) {
                if (mEntities != oldEntities) {
                    // Multiple async tasks were in flight and we
                    // lost the race.
                    return;
                }
                mEntities = newEntities;
                mHasEntities = true;
            }
            considerBindData();
        }
    }).execute();
}

From source file:info.guardianproject.otr.app.im.app.WelcomeActivity.java

private void completeShutdown() {
    new AsyncTask<String, Void, String>() {

        private ProgressDialog dialog;

        @Override//w w  w .j  a  va 2s .  c o m
        protected void onPreExecute() {
            if (mApp.getActiveConnections().size() > 0) {
                dialog = new ProgressDialog(WelcomeActivity.this);
                dialog.setCancelable(true);
                dialog.setMessage(getString(R.string.signing_out_wait));
                dialog.show();
            }
        }

        @Override
        protected String doInBackground(String... params) {

            boolean stillConnected = true;

            while (stillConnected) {

                try {
                    IImConnection conn = mApp.getActiveConnections().iterator().next();

                    if (conn.getState() == ImConnection.DISCONNECTED
                            || conn.getState() == ImConnection.LOGGING_OUT) {
                        stillConnected = false;
                    } else {
                        conn.logout();
                        stillConnected = true;
                    }

                    Thread.sleep(500);
                } catch (Exception e) {
                }

            }

            return "";
        }

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

            if (dialog != null)
                dialog.dismiss();

            mApp.forceStopImService();

            Imps.clearPassphrase(mApp);

            if (mCacheWord != null) {
                mCacheWord.manuallyLock();
            }

            Intent cacheWordIntent = CacheWordService.getBlankServiceIntent(getApplicationContext());
            stopService(cacheWordIntent);
            finish();
        }
    }.execute();

}

From source file:export.UploadManager.java

private void doUpload(final Uploader uploader) {
    final ProgressDialog copySpinner = mSpinner;
    final SQLiteDatabase copyDB = mDBHelper.getWritableDatabase();

    copySpinner.setMessage("Uploading " + uploader.getName());

    new AsyncTask<Uploader, String, Uploader.Status>() {

        @Override//from  w w w  .j a v  a 2  s .  co m
        protected Uploader.Status doInBackground(Uploader... params) {
            try {
                return params[0].upload(copyDB, mID);
            } catch (Exception ex) {
                ex.printStackTrace();
                return Uploader.Status.ERROR;
            }
        }

        @Override
        protected void onPostExecute(Uploader.Status result) {
            switch (result) {
            case CANCEL:
                disableUploader(disableUploaderCallback, uploader, false);
                return;
            case SKIP:
            case ERROR:
            case INCORRECT_USAGE:
                nextUploader();
                return;
            case OK:
                uploadOK(uploader, copySpinner, copyDB, mID);
                nextUploader();
                return;
            case NEED_AUTH: // should be handled inside connect "loop"
                handleAuth(new Callback() {
                    @Override
                    public void run(String uploaderName, Uploader.Status status) {
                        switch (status) {
                        case CANCEL:
                            disableUploader(disableUploaderCallback, uploader, false);
                            return;
                        case SKIP:
                        case ERROR:
                        case INCORRECT_USAGE:
                        case NEED_AUTH: // should be handled inside
                                        // connect "loop"
                            nextUploader();
                            return;
                        case OK:
                            doUpload(uploader);
                            return;
                        }
                    }
                }, uploader, result.authMethod);
                return;
            }
        }
    }.execute(uploader);
}

From source file:com.perm.DoomPlay.PlayingService.java

private void loadMusic() {
    dispose();//from ww  w  .ja va 2  s.c o  m

    //TODO: sometimes it throws  java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 , it's need to be fixed
    if (audios == null || audios.size() == 0)
        return;
    updateWidgets();
    sendBroadcast(new Intent(actionTrackChanged));
    if (isPlaying)
        sendBroadcast(new Intent(actionIconPause));
    else
        sendBroadcast(new Intent(actionIconPlay));

    startNotif();
    setBroadcast();

    new AsyncTask<Void, String, Void>() {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isLoadingTrack = true;

            if (loadingListener != null)
                loadingListener.onLoadingTrackStarted();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                if (isOnline)
                    bassPlayer.prepareNet(audios.get(indexCurrentTrack).getUrl());

                else
                    bassPlayer.prepareFile(audios.get(indexCurrentTrack).getUrl());
            } catch (IOException e) {
                cancel(false);
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();

            isLoadingTrack = false;
            if (loadingListener != null)
                loadingListener.onLoadingTrackEnded();

            Toast.makeText(getBaseContext(), getResources().getString(R.string.error), Toast.LENGTH_SHORT)
                    .show();
            isPlaying = false;

            sendBroadcast(new Intent(actionIconPlay));
            sendBroadcast(new Intent(SmallWidget.actionUpdateWidget));
            startNotif();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            isPrepared = true;

            isLoadingTrack = false;
            if (loadingListener != null)
                loadingListener.onLoadingTrackEnded();

            if (isPlaying) {
                bassPlayer.start();
            }

            Bitmap tempBitmap = AlbumArtGetter.getBitmapFromStore(audios.get(indexCurrentTrack).getAid(),
                    getBaseContext());

            if (tempBitmap == null)
                downloadAlbumArt(audios.get(indexCurrentTrack));
            else
                tempBitmap.recycle();
        }
    }.execute();

}

From source file:com.firescar96.nom.GCMIntentService.java

/**
 * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP
 * or CCS to send messages to your app. Not needed for this demo since the
 * device sends upstream messages to a server that echoes back the message
 * using the 'from' address in the message.
 * @return //from   w  w w  .  jav  a2 s  .c  om
 */
public static String sendRegistrationIdToBackend() {
    String msg = "";
    new AsyncTask<Object, Object, Object>() {
        @Override
        protected Object doInBackground(Object... param) {
            String msg = "";
            InputStream inputStream = null;

            try {
                // 1. create HttpClient
                HttpClient httpclient = new DefaultHttpClient();

                // 2. make POST request to the given URL
                HttpPost httpPost = new HttpPost("http://nchinda2.mit.edu:666");

                String json = "";

                // 3. build jsonObject
                JSONObject jsonObject = new JSONObject();
                jsonObject.accumulate("regId", regId);
                jsonObject.accumulate("host", MainActivity.appData.getString("host"));

                // 4. convert JSONObject to JSON to String
                json = jsonObject.toString();

                // 5. set json to StringEntity
                StringEntity se = new StringEntity(json);

                // 6. set httpPost Entity
                httpPost.setEntity(se);

                // 7. Set some headers to inform server about the type of the content   
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");

                HttpParams httpParams = httpclient.getParams();
                HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
                HttpConnectionParams.setSoTimeout(httpParams, 5000);
                httpPost.setParams(httpParams);

                // 8. Execute POST request to the given URL
                System.out.println("executing" + json);
                HttpResponse httpResponse = httpclient.execute(httpPost);
                // 9. receive response as inputStream
                inputStream = httpResponse.getEntity().getContent();

                // 10. convert inputstream to string
                if (inputStream != null)
                    msg = convertInputStreamToString(inputStream);
                else
                    msg = "Did not work!";

            } catch (Exception e) {
                e.printStackTrace();
                ;
            }
            System.out.println(msg);
            return msg;
        }
    }.execute(null, null, null);
    System.out.println(msg);
    return msg;
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

private static void showMedia(final String localId, final Context ctx, final ProgressDialog dialog) {
    new AsyncTask<Void, Void, Boolean>() {

        private boolean noMedia = false;

        @Override/*  w ww  .  ja  v  a 2 s.c  o  m*/
        protected Boolean doInBackground(Void... params) {
            File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
            File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);

            Intent mediaPlayer = new Intent(Intent.ACTION_VIEW);

            if (file1.exists()) {
                mediaPlayer.setDataAndType(Uri.fromFile(file1), "image/*");
            } else if (file2.exists()) {
                mediaPlayer.setDataAndType(Uri.fromFile(file2), "video/*");

            } else {
                noMedia = true;
                return false;
            }
            ctx.startActivity(mediaPlayer);
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            if (noMedia) {
                Toast.makeText(ctx.getApplicationContext(),
                        ctx.getApplicationContext().getText(R.string.no_media), Toast.LENGTH_SHORT).show();
                noMedia = false;
            }
        }

    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

}

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

/**
 * ???ID???./*  w w w . ja  va2s . co  m*/
 * 
 * @param deviceId ?ID
 * @param listener 
 */
public static void asynTakePhoto(final String deviceId, 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();
                HttpPost request = new HttpPost(MEDIASTREAM_RECORDING_URI + "?deviceId=" + deviceId + "&"
                        + DConnectMessage.EXTRA_ACCESS_TOKEN + "=" + accessToken);
                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:com.afrozaar.jazzfestreporting.MainActivity.java

private void directTag(final VideoData video) {
    final Video updateVideo = new Video();
    VideoSnippet snippet = video.addTags(Arrays.asList(Constants.DEFAULT_KEYWORD,
            Upload.generateKeywordFromPlaylistId(Constants.UPLOAD_PLAYLIST)));
    updateVideo.setSnippet(snippet);/* w w w.  j  a  v  a 2 s.  c  o  m*/
    updateVideo.setId(video.getYouTubeId());

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {

            YouTube youtube = new YouTube.Builder(transport, jsonFactory, credential)
                    .setApplicationName(Constants.APP_NAME).build();
            try {
                youtube.videos().update("snippet", updateVideo).execute();
            } catch (UserRecoverableAuthIOException e) {
                startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
            return null;
        }

    }.execute((Void) null);
    Toast.makeText(this, R.string.video_submitted_to_ytdl, Toast.LENGTH_LONG).show();
}