List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:ca.ualberta.cmput301.t03.trading.TradeOfferHistoryFragment.java
/** * Sets up the view components for the view, and sets the current model. * * @param savedInstanceState/* w w w . j av a 2s. c om*/ */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); AsyncTask worker = new AsyncTask() { @Override protected void onPreExecute() { super.onPreExecute(); // TODO show loading indicator } @Override protected Object doInBackground(Object[] params) { try { model = PrimaryUser.getInstance().getTradeList(); } catch (IOException e) { ExceptionUtils.toastErrorWithNetwork(); } catch (ServiceNotAvailableException e) { ExceptionUtils.toastErrorWithNetwork(); } return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); // todo hide loading indicator setupListView(getContext()); observeModel(); } }; worker.execute(); }
From source file:net.kourlas.voipms_sms.Billing.java
public void preDonation(final Activity sourceActivity) { try {/*from ww w . j a v a 2s . c o m*/ Bundle ownedItems = billingService.getPurchases(3, applicationContext.getPackageName(), "inapp", null); int response = ownedItems.getInt("RESPONSE_CODE"); if (response == 0) { List<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST"); for (String purchaseData : purchaseDataList) { JSONObject json = new JSONObject(purchaseData); String pid = json.getString("productId"); final String token = json.getString("purchaseToken"); if (pid.equals(applicationContext.getString(R.string.billing_pid_donation))) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { billingService.consumePurchase(3, sourceActivity.getPackageName(), token); } catch (Exception ignored) { // Do nothing. } return null; } @Override protected void onPostExecute(Void aVoid) { showDonationDialog(sourceActivity); } }.execute(); return; } } } } catch (Exception ignored) { // Do nothing. } showDonationDialog(sourceActivity); }
From source file:com.example.hellojni.HelloJni.java
@Override public void onResume() { super.onResume(); /*//from ww w . j a v a 2s .co m ByteBuffer buffer = vk.doStuff(); if (buffer != null) { Log.d("HelloJni", "Got buffer from jni:" + buffer.capacity()); Bitmap frame = Bitmap.createBitmap(192, 144, Config.ARGB_8888); frame.copyPixelsFromBuffer(buffer); ImageView iv = new ImageView(this); iv.setImageBitmap(frame); setContentView(iv); } */ /* new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... params) { vk.doStuff(frame); return null; } }.execute(); */ new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... ps) { HttpPost post = new HttpPost("http://192.168.0.187:45631/service"); AVMap avMap = new AVMap("air.connect.Request"); avMap.put("requestURL", "http://192.168.0.187:45631/service"); avMap.put("clientVersion", 240); avMap.put("serviceName", "browseService"); avMap.put("methodName", "getItems"); avMap.put("clientIdentifier", "89eae483355719f119d698e8d11e8b356525ecfb"); AVMap params = new AVMap("air.video.BrowseRequest"); params.put("folderId", "5ADB62B1BB62E0190E4B9C07159265C48F322D84"); params.put("preloadDetails", 0); List<Object> list = new ArrayList<Object>(); list.add(params); avMap.put("parameters", list); AVStream avStream = new AVStream(); avStream.write(avMap, 0); post.setEntity(new ByteArrayEntity(avStream.finish())); try { HttpResponse response = httpClient.execute(post); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); response.getEntity().writeTo(outputStream); AVStream result = new AVStream(outputStream.toByteArray()); AVMap foo = (AVMap) result.read(); Log.d("AirVideo", foo.getName()); Log.d("AirVideo", foo.toString()); AVMap results = (AVMap) foo.get("result"); final List<Object> items = (List<Object>) results.get("items"); runOnUiThread(new Runnable() { public void run() { // TODO Auto-generated method stub for (Object o : items) { AVMap item = (AVMap) o; listAdapter.add((String) item.get("name")); } } }); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }.execute(); }
From source file:com.ionicsdk.discovery.Discovery.java
public void doIdentify(final JSONObject opts, final CallbackContext callbackContext) { new AsyncTask<Integer, Void, Void>() { @Override/*from w w w . j a v a 2s . c o m*/ protected Void doInBackground(Integer... params) { try { DatagramSocket socket = new DatagramSocket(); socket.setBroadcast(true); String data = opts.toString(); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), getBroadcastAddress(), opts.getInt("port")); socket.send(packet); Log.d(TAG, "Sent packet"); byte[] buf = new byte[1024]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String result = new String(buf, 0, packet.getLength()); Log.d(TAG, "Got response packet of " + packet.getLength() + " bytes: " + result); callbackContext.success(result); } catch (Exception e) { callbackContext.error(e.getMessage()); Log.e(TAG, "Exception while listening for server broadcast"); e.printStackTrace(); } return null; } }.execute(); }
From source file:com.socialize.auth.twitter.TwitterOAuthProvider.java
public void retrieveAccessTokenAsync(final OAuthConsumer consumer, final String oauthVerifier, final OAuthTokenListener listener) { new AsyncTask<Void, Void, Void>() { HttpParameters httpParameters = new HttpParameters(); Exception error;//from w w w. j av a2s .c o m @Override protected Void doInBackground(Void... params) { try { retrieveAccessToken(consumer, oauthVerifier, new OAuthTokenListener() { @Override public void onResponse(HttpParameters parameters) { httpParameters.merge(parameters); } @Override public void onError(Exception e) { error = e; } }); } catch (Exception e) { error = e; } return null; } @Override protected void onPostExecute(Void result) { if (listener != null) { if (error != null) { listener.onError(error); } else { listener.onResponse(httpParameters); } } } }.execute(); }
From source file:com.clover.android.sdk.examples.WebServiceActivity.java
private void queryWebService() { new AsyncTask<Void, String, Void>() { @Override//from w ww. j a va 2 s . com protected void onProgressUpdate(String... values) { String logString = values[0]; log(logString); } @Override protected Void doInBackground(Void... params) { try { publishProgress("Requesting auth token"); CloverAuth.AuthResult authResult = CloverAuth.authenticate(WebServiceActivity.this, mAccount); publishProgress("Successfully authenticated as " + mAccount + ". authToken=" + authResult.authToken + ", authData=" + authResult.authData); if (authResult.authToken != null && authResult.baseUrl != null) { CustomHttpClient httpClient = CustomHttpClient.getHttpClient(); String getNameUri = "/v2/merchant/name"; String url = authResult.baseUrl + getNameUri + "?access_token=" + authResult.authToken; publishProgress("requesting merchant id using: " + url); String result = httpClient.get(url); JSONTokener jsonTokener = new JSONTokener(result); JSONObject root = (JSONObject) jsonTokener.nextValue(); String merchantId = root.getString("merchantId"); publishProgress("received merchant id: " + merchantId); // now do another get using the merchant id String inventoryUri = "/v2/merchant/" + merchantId + "/inventory/items"; url = authResult.baseUrl + inventoryUri + "?access_token=" + authResult.authToken; publishProgress("requesting inventory items using: " + url); result = httpClient.get(url); publishProgress("received inventory items response: " + result); } } catch (Exception e) { publishProgress("Error retrieving merchant info from server" + e); } return null; } @Override protected void onPostExecute(Void aVoid) { mButton.setEnabled(true); } }.execute(); }
From source file:ca.rmen.android.palidamuerte.app.poem.detail.PoemDetailFragment.java
private void updateView(final Activity activity, final View rootView) { Log.v(TAG, "updateView"); new AsyncTask<Void, Void, PoemCursor>() { @Override//from w ww . j av a 2s . c o m protected PoemCursor doInBackground(Void... params) { if (getArguments().containsKey(ARG_ITEM_ID)) { long poemId = getArguments().getLong(ARG_ITEM_ID); PoemCursor poemCursor = new PoemSelection().id(poemId).query(activity.getContentResolver()); if (poemCursor.moveToFirst()) return poemCursor; poemCursor.close(); } return null; } @Override protected void onPostExecute(PoemCursor poemCursor) { boolean favorite = poemCursor.getIsFavorite(); if (favorite != mIsFavorite) { mIsFavorite = favorite; activity.invalidateOptionsMenu(); } TextView tvTitleView = (TextView) rootView.findViewById(R.id.title); tvTitleView.setText(poemCursor.getTitle()); String preContent = poemCursor.getPreContent(); TextView preContentView = (TextView) rootView.findViewById(R.id.pre_content); preContentView.setVisibility(TextUtils.isEmpty(preContent) ? View.GONE : View.VISIBLE); preContentView.setText(preContent); ((TextView) rootView.findViewById(R.id.content)).setText(poemCursor.getContent()); String poemTypeAndNumber = Poems.getPoemNumberString(activity, poemCursor); TextView tvPoemTypeAndNumber = (TextView) rootView.findViewById(R.id.poem_type_and_number); tvPoemTypeAndNumber.setVisibility(TextUtils.isEmpty(poemTypeAndNumber) ? View.GONE : View.VISIBLE); tvPoemTypeAndNumber.setText(poemTypeAndNumber); String locationDateString = Poems.getLocationDateString(activity, poemCursor); ((TextView) rootView.findViewById(R.id.author)).setText(R.string.author); ((TextView) rootView.findViewById(R.id.location_and_date)).setText(locationDateString); poemCursor.close(); } }.execute(); }
From source file:com.google.android.gcm.demo.app.DemoActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkNotNull(SERVER_URL, "SERVER_URL"); checkNotNull(SENDER_ID, "SENDER_ID"); // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(this); setContentView(R.layout.main);// w w w . j a v a 2 s . c o m mDisplay = (TextView) findViewById(R.id.display); registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); final String regId = GCMRegistrar.getRegistrationId(this); final Context context = this; if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(this, SENDER_ID); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration. mDisplay.append(getString(R.string.already_registered) + "\n"); } else { // Try to register again, but not in the UI thread. // It's also necessary to cancel the thread onDestroy(), // hence the use of AsyncTask instead of a raw thread. mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { boolean registered = ServerUtilities.register(context, regId); // At this point all attempts to register with the app // server failed, so we need to unregister the device // from GCM - the app will try to register again when // it is restarted. Note that GCM will send an // unregistered callback upon completion, but // GCMIntentService.onUnregistered() will ignore it. if (!registered) { GCMRegistrar.unregister(context); } return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } } MyTask task = new MyTask(); task.execute(); }
From source file:weavebytes.com.futureerp.activities.RegistrationActivity.java
public void SendRegRequest() { new AsyncTask<Void, Void, String>() { @Override/* ww w .j a va 2 s .com*/ protected void onPreExecute() { super.onPreExecute(); progress.setMessage("Please Wait.."); progress.setProgressStyle(ProgressDialog.STYLE_SPINNER); progress.setCancelable(true); progress.show(); } @Override protected String doInBackground(Void... params) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Config.URL_REGISTER); List<NameValuePair> nameValuePair = new ArrayList<>(); nameValuePair.add(new BasicNameValuePair("email", email)); nameValuePair.add(new BasicNameValuePair("username", username)); nameValuePair.add(new BasicNameValuePair("password", password)); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); } catch (UnsupportedEncodingException e) { return e + ""; } try { HttpResponse response = httpClient.execute(httpPost); Log.d("Http Post Response:", response.toString()); //Converting Response To JsonString return ConvertResponse_TO_JSON.entityToString(response.getEntity()); } catch (ClientProtocolException e) { // Log exception e.printStackTrace(); } catch (IOException e) { // Log exception e.printStackTrace(); } return "Bad NetWork"; } @Override protected void onPostExecute(String JsonString) { Toast.makeText(RegistrationActivity.this, JsonString, Toast.LENGTH_SHORT).show(); JSONObject jsonobj = null; progress.dismiss(); try { jsonobj = new JSONObject(JsonString); //Parsing JSON and Checking the error_code (username ot password are correct or not) if (jsonobj.getString("error").equals("0")) { Intent intent = new Intent(RegistrationActivity.this, LoginActivity.class); startActivity(intent); finish(); } else { Toast.makeText(RegistrationActivity.this, "Failed to register", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }.execute(); }
From source file:com.clutch.ClutchAPIClient.java
private static void sendRequest(String url, boolean post, JSONObject payload, String version, final ClutchAPIResponseHandler responseHandler) { BasicHeader[] headers = { new BasicHeader("X-App-Version", version), new BasicHeader("X-UDID", ClutchUtils.getUDID()), new BasicHeader("X-API-Version", VERSION), new BasicHeader("X-App-Key", appKey), new BasicHeader("X-Bundle-Version", versionName), new BasicHeader("X-Platform", "Android"), }; StringEntity entity = null;/*from w ww . j a va2 s.co m*/ try { entity = new StringEntity(payload.toString()); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Could not encode the JSON payload and attach it to the request: " + payload.toString()); return; } HttpRequestBase request = null; if (post) { request = new HttpPost(url); ((HttpEntityEnclosingRequestBase) request).setEntity(entity); request.setHeaders(headers); } else { request = new HttpGet(url); } class StatusCodeAndResponse { public int statusCode; public String response; public StatusCodeAndResponse(int statusCode, String response) { this.statusCode = statusCode; this.response = response; } } new AsyncTask<HttpRequestBase, Void, StatusCodeAndResponse>() { @Override protected StatusCodeAndResponse doInBackground(HttpRequestBase... requests) { try { HttpResponse resp = client.execute(requests[0]); HttpEntity entity = resp.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); int readBytes = 0; byte[] sBuffer = new byte[512]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } inputStream.close(); String response = new String(content.toByteArray()); content.close(); return new StatusCodeAndResponse(resp.getStatusLine().getStatusCode(), response); } catch (IOException e) { if (responseHandler instanceof ClutchAPIDownloadResponseHandler) { ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(e, ""); } else { responseHandler.onFailure(e, null); } } return null; } @Override protected void onPostExecute(StatusCodeAndResponse resp) { if (responseHandler instanceof ClutchAPIDownloadResponseHandler) { if (resp.statusCode == 200) { ((ClutchAPIDownloadResponseHandler) responseHandler).onSuccess(resp.response); } else { ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(null, resp.response); } } else { if (resp.statusCode == 200) { responseHandler.handleSuccessMessage(resp.response); } else { responseHandler.handleFailureMessage(null, resp.response); } } } }.execute(request); }