List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:com.torrenttunes.android.model.MusicProvider.java
/** * Get the list of music tracks from a server and caches the track information * for future reference, keying tracks by musicId and grouping by genre. *//*from ww w. j a va 2 s.c o m*/ public void retrieveMediaAsync(final Callback callback) { LogHelper.d(TAG, "retrieveMediaAsync called"); if (mCurrentState == State.INITIALIZED) { // Nothing to do, execute callback immediately callback.onMusicCatalogReady(true); return; } // Asynchronously load the music catalog in a separate thread new AsyncTask<Void, Void, State>() { @Override protected State doInBackground(Void... params) { retrieveArtists(); return mCurrentState; } @Override protected void onPostExecute(State current) { if (callback != null) { callback.onMusicCatalogReady(current == State.INITIALIZED); } } }.execute(); }
From source file:tmnt.wheresyourcar.ParkActivity.java
/** * Registers the application with GCM servers asynchronously. * <p>/* w ww .j av a 2s .co m*/ * Stores the registration ID and the 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); msg = "Device registered, registration ID=" + regid; 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; } }.execute(null, null, null); }
From source file:gstb.fd.eofficial.oa.im.widget.chatrow.EaseChatRowVoicePlayClickListener.java
@Override public void onClick(View v) { String st = activity.getResources().getString(R.string.Is_download_voice_click_later); if (isPlaying) { // if (playMsgId != null && playMsgId.equals(message.getMsgId())) { // currentPlayListener.stopPlayVoice(); // return; // } currentPlayListener.stopPlayVoice(); }/*from w w w .ja v a 2s . co m*/ if (message.direct() == EMMessage.Direct.SEND) { // for sent msg, we will try to play the voice file directly playVoice(message.getExt()); } else { if (message.status() == EMMessage.Status.SUCCESS) { File file = new File(message.getExt()); if (file.exists()) { playVoice(message.getExt()); } else { Log.e(TAG, "file not exist"); Toast.makeText(activity, st, Toast.LENGTH_SHORT).show(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // EMClient.getInstance().chatManager().downloadAttachment(message); try { Log.e(TAG, "file not exist1"); IMFileUtils.down_file(IMConstants.path + message.getFileId(), message.getExt()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); adapter.notifyDataSetChanged(); } }.execute(); } } else if (message.status() == EMMessage.Status.INPROGRESS) { Toast.makeText(activity, st, Toast.LENGTH_SHORT).show(); } else if (message.status() == EMMessage.Status.FAIL) { Toast.makeText(activity, st, Toast.LENGTH_SHORT).show(); } } }
From source file:com.shafiq.myfeedle.core.SelectFriends.java
protected void loadFriends() { mFriends.clear();/*from ww w. ja va2s . c o m*/ // SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected}); SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected }); setListAdapter(sa); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() { @Override protected Boolean doInBackground(Long... params) { boolean loadList = false; MyfeedleCrypto myfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext()); // load the session Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?", new String[] { Long.toString(params[0]) }, null); if (account.moveToFirst()) { mToken = myfeedleCrypto.Decrypt(account.getString(0)); mSecret = myfeedleCrypto.Decrypt(account.getString(1)); mService = account.getInt(2); } account.close(); String response; switch (mService) { case TWITTER: break; case FACEBOOK: if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet( String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) { try { JSONArray friends = new JSONObject(response).getJSONArray(Sdata); for (int i = 0, l = friends.length(); i < l; i++) { JSONObject f = friends.getJSONObject(i); HashMap<String, String> newFriend = new HashMap<String, String>(); newFriend.put(Entities.ESID, f.getString(Sid)); newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid))); newFriend.put(Entities.FRIEND, f.getString(Sname)); // need to alphabetize if (mFriends.isEmpty()) mFriends.add(newFriend); else { String fullName = f.getString(Sname); int spaceIdx = fullName.lastIndexOf(" "); String newFirstName = null; String newLastName = null; if (spaceIdx == -1) newFirstName = fullName; else { newFirstName = fullName.substring(0, spaceIdx++); newLastName = fullName.substring(spaceIdx); } List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>(); for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) { HashMap<String, String> oldFriend = mFriends.get(i2); if (newFriend == null) { newFriends.add(oldFriend); } else { fullName = oldFriend.get(Entities.FRIEND); spaceIdx = fullName.lastIndexOf(" "); String oldFirstName = null; String oldLastName = null; if (spaceIdx == -1) oldFirstName = fullName; else { oldFirstName = fullName.substring(0, spaceIdx++); oldLastName = fullName.substring(spaceIdx); } if (newFirstName == null) { newFriends.add(newFriend); newFriend = null; } else { int comparison = oldFirstName.compareToIgnoreCase(newFirstName); if (comparison == 0) { // compare firstnames if (newLastName == null) { newFriends.add(newFriend); newFriend = null; } else if (oldLastName != null) { comparison = oldLastName.compareToIgnoreCase(newLastName); if (comparison == 0) { newFriends.add(newFriend); newFriend = null; } else if (comparison > 0) { newFriends.add(newFriend); newFriend = null; } } } else if (comparison > 0) { newFriends.add(newFriend); newFriend = null; } } newFriends.add(oldFriend); } } if (newFriend != null) newFriends.add(newFriend); mFriends = newFriends; } } loadList = true; } catch (JSONException e) { Log.e(TAG, e.toString()); } } break; case MYSPACE: break; case LINKEDIN: break; case FOURSQUARE: break; case IDENTICA: break; case GOOGLEPLUS: break; case CHATTER: break; } return loadList; } @Override protected void onPostExecute(Boolean loadList) { if (loadList) { // SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name}); SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected }); sa.setViewBinder(mViewBinder); setListAdapter(sa); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); } }; 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(mAccountId); }
From source file:com.juanojfp.gcmsample.MainActivity.java
/** * Registers the application with GCM servers asynchronously. * <p>//w w w. ja va2 s . c o m * Stores the registration id, app versionCode, and expiration time in the application's * shared preferences. */ private void registerBackground() { 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); // 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. msg = registerInServer(regid); // Save the regid - no need to register again. setRegistrationId(context, regid); } catch (IOException ex) { ex.printStackTrace(); msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); }
From source file:com.df.push.DemoActivity.java
/** * Registers the application with GCM servers asynchronously. * <p>/*w w w. j a va 2 s .c o m*/ * Stores the registration ID and the 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); 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. sendRegistrationIdToBackend(regid); 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"); Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show(); progressDialog.dismiss(); } @Override protected void onPreExecute() { if (progressDialog != null) progressDialog.show(); }; }.execute(null, null, null); }
From source file:org.jboss.aerogear.android.sync.SyncService.java
private void connectAsync() { AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override//w w w . j a va 2s . c o m protected Void doInBackground(Void... params) { try { syncClient.connect(); } catch (Exception ex) { Log.e(TAG, ex.getMessage(), ex); throw new RuntimeException(ex); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); for (SyncServerConnectionListener listener : connectionListeners) { listener.onConnected(); } } }; task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null); }
From source file:com.example.touchdbtest.CouchbaseUtils.java
protected static void startEktorp() { Log.v(TAG, "starting ektorp"); if (httpClient != null) { httpClient.shutdown();// w w w . ja v a2 s.c o m } httpClient = new TouchDBHttpClient(server); dbInstance = new StdCouchDbInstance(httpClient); SyncEktorpAsyncTask startupTask = new SyncEktorpAsyncTask() { @Override protected void doInBackground() { connectorVehicle = dbInstance.createConnector(DATABASE_VEHICLE, true); } @Override protected void onSuccess() { // init the vendor and tenant info // try to reconnect to socket if not connected every 3 seconds // this delay also allows socket to establish itself new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { String url = "http://10.100.131.157:5984"; startPullReplications(url, DATABASE_VEHICLE); return null; } }.execute(); } }; startupTask.execute(); }
From source file:com.quantcast.measurement.service.QCLocation.java
private void sendLocation(Location location) { final Double lat = location.getLatitude(); final Double longTemp = location.getLongitude(); _geoTask = new AsyncTask<Double, Void, MeasurementLocation>() { @Override/*w ww . j a v a 2 s . c o m*/ protected MeasurementLocation doInBackground(Double... params) { MeasurementLocation retval; double latitude = params[0]; double longitude = params[1]; QCLog.i(TAG, "Looking for address."); try { QCLog.i(TAG, "Geocoder."); List<Address> addresses = _geocoder.getFromLocation(latitude, longitude, 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); retval = new MeasurementLocation(address.getCountryCode(), address.getAdminArea(), address.getLocality(), address.getPostalCode()); } else { QCLog.i(TAG, "Geocoder reverse lookup failed."); retval = this.fallbackGeoLocate(latitude, longitude); } } catch (Exception e) { QCLog.i(TAG, "Geocoder API not available."); retval = this.fallbackGeoLocate(latitude, longitude); } return retval; } protected MeasurementLocation fallbackGeoLocate(double latitude, double longitude) { MeasurementLocation retval = null; // call googles map api directly MeasurementLocation geoInfo = lookup(latitude, longitude); if (geoInfo != null && !this.isCancelled()) { retval = geoInfo; } else { QCLog.i(TAG, "Google Maps API reverse lookup failed."); } return retval; } @Override protected void onPostExecute(MeasurementLocation address) { if (null != address && address.getCountry() != null) { QCLog.i(TAG, "Got address and sending..." + address.getCountry() + " " + address.getState() + " " + address.getLocality()); HashMap<String, String> params = new HashMap<String, String>(); params.put(QCEvent.QC_EVENT_KEY, QC_EVENT_LOCATION); if (address.getCountry() != null) { params.put(QC_COUNTRY_KEY, address.getCountry()); } if (address.getState() != null) { params.put(QC_STATE_KEY, address.getState()); } if (address.getLocality() != null) { params.put(QC_CITY_KEY, address.getLocality()); } if (address.getPostalCode() != null) { params.put(QC_POSTALCODE_KEY, address.getPostalCode()); } QCMeasurement.INSTANCE.logOptionalEvent(params, null, null); } } }; //Async execute needs to be on main thread if (Looper.getMainLooper().getThread() == Thread.currentThread()) { if (_geoTask != null && _geoTask.getStatus() == AsyncTask.Status.PENDING) { _geoTask.execute(lat, longTemp); } } else { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (_geoTask != null && _geoTask.getStatus() == AsyncTask.Status.PENDING) { _geoTask.execute(lat, longTemp); } } }); } }
From source file:be.evias.cloudLogin.cloudLoginMainActivity.java
private void processLogoutServerSide(final Account account) { new AsyncTask<String, Void, Intent>() { @Override//from www .j av a2 s .c o m protected Intent doInBackground(String... params) { Bundle data = new Bundle(); try { sServerAuthenticate.userSignOut(mContext, account.name); data.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); Log.d("cloudLogin", "cloudloginMainActivity/logoutAccount: userSignOut successful."); showMessage(mContext.getString(R.string.message_logout_success), Toast.LENGTH_SHORT); } catch (Exception e) { Log.d("cloudLogin", "cloudloginMainActivity/logoutAccount: userSignOut error."); e.printStackTrace(); data.putString(KEY_ERROR_MESSAGE, e.getMessage()); } final Intent res = new Intent(); res.putExtras(data); return res; } @Override protected void onPostExecute(Intent intent) { if (intent.hasExtra(KEY_ERROR_MESSAGE)) Toast.makeText(getBaseContext(), intent.getStringExtra(KEY_ERROR_MESSAGE), Toast.LENGTH_SHORT) .show(); else finishLogout(intent); } }.execute(); }