List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:uk.bowdlerize.MainActivity.java
private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override/*from ww w . j av a 2 s . c o m*/ 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. // 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(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"); } }.execute(null, null, null); }
From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java
/** * ???./*from w w w . ja v a2 s . co m*/ * * @param deviceId ?ID * @param sessionKey ID * @param listener */ public static void asyncUnregisterDiscovery(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( DISCOVERY_CHANGE_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:com.example.caique.educam.Activities.TimelineActivity.java
private void retrievePosts(String user, String type) { mAsyncTask = new AsyncTask<String, Void, Request>() { private JSONObject rawJson = new JSONObject(); private Request checkReq = new Request(); @Override//from ww w . j av a 2s. co m protected void onPreExecute() { super.onPreExecute(); mProgressBar.setVisibility(View.VISIBLE); mProgressBar.setEnabled(true); } @Override protected Request doInBackground(String... strings) { try { if (!strings[0].isEmpty()) { rawJson.put("user", strings[0]); } if (!strings[1].isEmpty()) { rawJson.put("type", strings[1]); checkReq.setType(strings[1]); } checkReq.setResponse(POST(rawJson)); return checkReq; } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Falha na conexo", Toast.LENGTH_SHORT).show(); } return null; } @Override protected void onPostExecute(Request request) { try { mProgressBar.setVisibility(View.INVISIBLE); mProgressBar.setEnabled(false); handleConnection(request); } catch (JSONException e) { e.printStackTrace(); } } }; mAsyncTask.execute(user, type); }
From source file:com.stepsdk.android.api.APIClient.java
public void post(final String address, final Map<String, String> params, final Map<String, String> files, final APIRequestHandler handler) { log(TAG, "POST: " + address + "(" + params.toString() + ")"); new AsyncTask<Void, Void, Void>() { private boolean mInterrupt = false; @Override//from w ww . j av a 2 s . c om protected void onPreExecute() { handler.before(); }; @Override protected Void doInBackground(Void... nothing) { Integer retryRemaining = 3; while (retryRemaining > 0) { try { if (!NetworkUtil.isOnline(mContext)) { handler.onException(new NetworkDownException()); return null; } HttpEntity response = null; if (files == null || files.size() == 0) response = postRequest(address, params); else response = postRequest(address, params, files); handler.onResponse(response); break; } catch (ClientProtocolException e) { if (retryRemaining-- < 0) { handler.onException(e); } } catch (IOException e) { if (retryRemaining-- < 0) { handler.onException(e); } } catch (NetworkDownException e) { if (retryRemaining-- < 0) { handler.onException(e); } } catch (HttpGetException e) { if (retryRemaining-- < 0) { handler.onException(e); } } catch (Exception e) { if (retryRemaining-- < 0) { handler.onException(e); } } } return null; }; @Override protected void onPostExecute(Void result) { if (!mInterrupt) handler.after(); }; }.execute(); }
From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java
public static void DownloadFromUrl(final String media, final String messageId, final Context ctx, final ImageView container, final Object object, final String timelineId, final String localId, final Long fileSize) { new AsyncTask<Void, Void, Boolean>() { private boolean retry = true; private Bitmap imageDownloaded; private BroadcastReceiver mDownloadCancelReceiver; private HttpGet job; private AccountManager am; private Account account; private String authToken; @Override/* ww w .j a va 2s .c o m*/ protected void onPreExecute() { IntentFilter downloadFilter = new IntentFilter(ConstantKeys.BROADCAST_CANCEL_PROCESS); mDownloadCancelReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String localIdToClose = (String) intent.getExtras().get(ConstantKeys.LOCALID); if (localId.equals(localIdToClose)) { try { job.abort(); } catch (Exception e) { log.debug("The process was canceled"); } cancel(false); } } }; // registering our receiver ctx.getApplicationContext().registerReceiver(mDownloadCancelReceiver, downloadFilter); } @Override protected void onCancelled() { File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG); File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP); if (file1.exists()) { file1.delete(); } if (file2.exists()) { file2.delete(); } file1 = null; file2 = null; System.gc(); try { ctx.getApplicationContext().unregisterReceiver(mDownloadCancelReceiver); } catch (Exception e) { log.debug("Receriver unregister from another code"); } for (int i = 0; i < AppUtils.getlistOfDownload().size(); i++) { if (AppUtils.getlistOfDownload().get(i).equals(localId)) { AppUtils.getlistOfDownload().remove(i); } } DataBasesAccess.getInstance(ctx.getApplicationContext()).MessagesDataBaseWriteTotal(localId, 100); Intent intent = new Intent(); intent.setAction(ConstantKeys.BROADCAST_DIALOG_DOWNLOAD_FINISH); intent.putExtra(ConstantKeys.LOCALID, localId); ctx.sendBroadcast(intent); if (object != null) { ((ProgressDialog) object).dismiss(); } } @Override protected Boolean doInBackground(Void... params) { try { File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG); File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP); // firt we are goint to search the local files if ((!file1.exists()) && (!file2.exists())) { account = AccountUtils.getAccount(ctx.getApplicationContext(), false); am = (AccountManager) ctx.getSystemService(Context.ACCOUNT_SERVICE); authToken = ConstantKeys.STRING_DEFAULT; authToken = am.blockingGetAuthToken(account, ctx.getString(R.string.account_type), true); MessagingClientService messageService = new MessagingClientService( ctx.getApplicationContext()); URL urlObj = new URL(Preferences.getServerProtocol(ctx), Preferences.getServerAddress(ctx), Preferences.getServerPort(ctx), ctx.getString(R.string.url_get_content)); String url = ConstantKeys.STRING_DEFAULT; url = Uri.parse(urlObj.toString()).buildUpon().build().toString() + timelineId + "/" + messageId + "/" + "content"; job = new HttpGet(url); // first, get free space FreeUpSpace(ctx, fileSize); messageService.getContent(authToken, media, messageId, timelineId, localId, false, false, fileSize, job); } if (file1.exists()) { imageDownloaded = decodeSampledBitmapFromPath(file1.getAbsolutePath(), 200, 200); } else if (file2.exists()) { imageDownloaded = ThumbnailUtils.createVideoThumbnail(file2.getAbsolutePath(), MediaStore.Images.Thumbnails.MINI_KIND); } if (imageDownloaded == null) { return false; } return true; } catch (Exception e) { deleteFiles(); return false; } } @Override protected void onPostExecute(Boolean result) { // We have the media try { ctx.getApplicationContext().unregisterReceiver(mDownloadCancelReceiver); } catch (Exception e) { log.debug("Receiver was closed on cancel"); } if (!(localId.contains(ConstantKeys.AVATAR))) { for (int i = 0; i < AppUtils.getlistOfDownload().size(); i++) { if (AppUtils.getlistOfDownload().get(i).equals(localId)) { AppUtils.getlistOfDownload().remove(i); } } DataBasesAccess.getInstance(ctx.getApplicationContext()).MessagesDataBaseWriteTotal(localId, 100); Intent intent = new Intent(); intent.setAction(ConstantKeys.BROADCAST_DIALOG_DOWNLOAD_FINISH); intent.putExtra(ConstantKeys.LOCALID, localId); ctx.sendBroadcast(intent); } if (object != null) { ((ProgressDialog) object).dismiss(); } // Now the only container could be the avatar in edit screen if (container != null) { if (imageDownloaded != null) { container.setImageBitmap(imageDownloaded); } else { deleteFiles(); imageDownloaded = decodeSampledBitmapFromResource(ctx.getResources(), R.drawable.ic_error_loading, 200, 200); container.setImageBitmap(imageDownloaded); Toast.makeText(ctx.getApplicationContext(), ctx.getApplicationContext().getText(R.string.donwload_fail), Toast.LENGTH_SHORT) .show(); } } else { showMedia(localId, ctx, (ProgressDialog) object); } } private void deleteFiles() { File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG); File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP); if (file1.exists()) { file1.delete(); } if (file2.exists()) { file2.delete(); } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
From source file:com.google.plus.wigwamnow.social.FacebookProvider.java
/** * Create a share action for the {@link Wigwam} on the Open Graph. *//*from www . j a v a2 s.c om*/ @Override public boolean structuredShare(Wigwam wigwam, Activity activity) { Session session = Session.getActiveSession(); if (session == null || !session.isOpened()) { return false; } if (!hasPublishPermissions()) { // Get user's permission to post OG Actions requestPublishPermissions(session, activity); return false; } final Activity hostActivity = activity; String postingString = activity.getResources().getString(R.string.posting); showProgressDialog(postingString, activity); final Wigwam toShare = wigwam; AsyncTask<Void, Void, Response> task = new AsyncTask<Void, Void, Response>() { @Override protected Response doInBackground(Void... params) { ShareAction shareAction = GraphObject.Factory.create(ShareAction.class); WigwamGraphObject wigwamObject = GraphObject.Factory.create(WigwamGraphObject.class); // Set wigwam URL String host = hostActivity.getResources().getString(R.string.external_host); String wigwamUrl = host + "/wigwams/" + toShare.getId().toString(); wigwamObject.setUrl(wigwamUrl); // Add wigwam shareAction.setWigwam(wigwamObject); // Post to OpenGraph Request request = new Request(Session.getActiveSession(), SHARE_ACTION_PATH, null, HttpMethod.POST); request.setGraphObject(shareAction); return request.executeAndWait(); } @Override protected void onPostExecute(Response response) { onPostActionResponse(response, hostActivity); } }; task.execute(); return true; }
From source file:com.moki.touch.fragments.views.WebContent.java
private boolean setLogo() { final ImageView logoView = (ImageView) rootView.findViewById(R.id.logo); boolean shouldListenForLogo = false; if (SettingsUtil.getUploadLogo() != null && !SettingsUtil.getUploadLogo().isEmpty()) { final Bitmap bitmapLogo = getLogoBitmap(); if (bitmapLogo == null) { shouldListenForLogo = true;/*from www . j av a2 s . co m*/ } else { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); logoView.setImageBitmap(bitmapLogo); } }.execute(); } } else { logoView.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.mt_web_logo)); } return shouldListenForLogo; }
From source file:com.abel.ooti.boss.DemoActivity.java
public void onClick(final View view) { if (view == findViewById(R.id.send)) { new AsyncTask<Void, Void, String>() { @Override// w w w . j av a 2 s.c o m protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.abel.ooti.gcm.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:ca.ualberta.cmput301.t03.user.FriendsListFragment.java
/** * {@inheritDoc}/* www .ja v a2s .co m*/ */ @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); addFriendFab = (FloatingActionButton) getActivity().findViewById(R.id.addFriendFab); mListView = (ListView) getActivity().findViewById(R.id.friendsListListView); mSwipeRefreshLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.friendsListSwipeLayout); AsyncTask worker = new AsyncTask() { @Override protected Object doInBackground(Object[] params) { try { mModel = mUser.getFriends(); mController = new FriendsListController(getContext(), mModel); } catch (IOException e) { e.printStackTrace(); } catch (ServiceNotAvailableException e) { throw new RuntimeException("App is offline.", e); } return null; } @Override protected void onPostExecute(Object o) { populateFields(); } }; worker.execute(); }
From source file:org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushRegistrar.java
@Override public void unregister(final Context context, final Callback<Void> callback) { new AsyncTask<Void, Void, Exception>() { @Override/*from w ww. jav a 2 s . c o m*/ protected Exception doInBackground(Void... params) { try { if (gcm == null) { gcm = gcmProvider.get(context); } gcm.unregister(); HttpProvider provider = httpProviderProvider.get(deviceRegistryURL, TIMEOUT); setPasswordAuthentication(variantId, secret, provider); try { provider.delete(deviceToken); deviceToken = ""; return null; } catch (HttpException ex) { return ex; } } catch (Exception ex) { return ex; } } @SuppressWarnings("unchecked") @Override protected void onPostExecute(Exception result) { if (result == null) { callback.onSuccess(null); } else { callback.onFailure(result); } } }.execute((Void) null); }