List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:com.example.m.niceproject.service.WeatherCacheService.java
public void save(Channel channel) { new AsyncTask<Channel, Void, Void>() { @Override// w ww . j av a2s .c om protected Void doInBackground(Channel[] channels) { FileOutputStream outputStream; try { outputStream = context.openFileOutput(CACHED_WEATHER_FILE, Context.MODE_PRIVATE); outputStream.write(channels[0].toJSON().toString().getBytes()); outputStream.close(); } catch (IOException e) { // TODO: file save operation failed } return null; } }.execute(channel); }
From source file:com.goliathonline.android.kegbot.util.BitmapUtils.java
/** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. * * @param cookie An arbitrary object that will be passed to the callback. *//* www .j a v a2 s .com*/ public static void fetchImage(final Context context, final String url, final BitmapFactory.Options decodeOptions, final Object cookie, final OnFetchCompleteListener callback) { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { final String url = params[0]; if (TextUtils.isEmpty(url)) { return null; } // First compute the cache key and cache file path for this URL File cacheFile = null; try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + context.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache bitmaps. } if (cacheFile != null && cacheFile.exists()) { Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions); if (cachedBitmap != null) { return cachedBitmap; } } try { // TODO: check for HTTP caching headers final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext()); final HttpResponse resp = httpClient.execute(new HttpGet(url)); final HttpEntity entity = resp.getEntity(); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK || entity == null) { return null; } final byte[] respBytes = EntityUtils.toByteArray(entity); // Write response bytes to cache. if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } // Decode the bytes and return the bitmap. return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions); } catch (Exception e) { Log.w(TAG, "Problem while loading image: " + e.toString(), e); } return null; } @Override protected void onPostExecute(Bitmap result) { callback.onFetchComplete(cookie, result); } }.execute(url); }
From source file:co.blustor.gatekeeperdemo.fragments.CardTaskFragment.java
private void preloadFaces() { new AsyncTask<Void, Void, GKFaces>() { @Override/*from ww w . java2 s .co m*/ protected GKFaces doInBackground(Void... params) { return Application.getGKFaces(); } @Override protected void onPostExecute(GKFaces faces) { synchronized (mSyncObject) { mFaces = faces; } if (mCallbacks != null) { mCallbacks.onFacesReady(mFaces); } } }.execute(); }
From source file:tw.idv.gasolin.pycontw2012.util.BitmapUtils.java
/** * Only call this method from the main (UI) thread. The * {@link OnFetchCompleteListener} callback be invoked on the UI thread, but * image fetching will be done in an {@link AsyncTask}. * /*ww w. j a v a 2s . c o m*/ * @param cookie * An arbitrary object that will be passed to the callback. */ public static void fetchImage(final Context context, final String url, final BitmapFactory.Options decodeOptions, final Object cookie, final OnFetchCompleteListener callback) { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { final String url = params[0]; if (TextUtils.isEmpty(url)) { return null; } // First compute the cache key and cache file path for this URL File cacheFile = null; try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + context.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache // bitmaps. } if (cacheFile != null && cacheFile.exists()) { Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions); if (cachedBitmap != null) { return cachedBitmap; } } try { // TODO: check for HTTP caching headers final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext()); final HttpResponse resp = httpClient.execute(new HttpGet(url)); final HttpEntity entity = resp.getEntity(); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK || entity == null) { return null; } final byte[] respBytes = EntityUtils.toByteArray(entity); // Write response bytes to cache. if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } // Decode the bytes and return the bitmap. return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions); } catch (Exception e) { Log.w(TAG, "Problem while loading image: " + e.toString(), e); } return null; } @Override protected void onPostExecute(Bitmap result) { callback.onFetchComplete(cookie, result); } }.execute(url); }
From source file:json2notification.app.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); jsonView = (TextView) findViewById(R.id.json); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String wikiJson = readFile("wiki.json"); jsonView.setText(wikiJson);// w w w . j a v a 2 s . c o m new AsyncTask<String, Void, Void>() { @Override public Void doInBackground(String... jsons) { android.util.Log.d("json2notification-app", "json:" + jsons[0]); //Notification n = Json2Notification.from(MainActivity.this).with(jsons[0]).notification(); //notificationManager.notify(1, n); //android.util.Log.d("json2notification-app", "notify:" + n); AndroidNotification androidNotification = AndroidNotification.parse(MainActivity.this, jsons[0]); android.util.Log.d("json2notification-app", "notify:" + androidNotification.android.notification); notificationManager.notify(1, androidNotification.android.notification); //android.util.Log.d("json2notification-app", "serialize:" + androidNotification.serialize()); return null; } }.execute(wikiJson); }
From source file:cc.softwarefactory.lokki.android.utilities.gcm.GcmHelper.java
private static void registerInBackground(final Context context) { new AsyncTask<Void, Void, String>() { @Override/*from www . j ava 2 s.co m*/ protected String doInBackground(Void... params) { try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); sendRegistrationIdToBackend(context); storeRegistrationId(context, regid); return "Device registered, registration ID = " + regid; } catch (IOException ex) { return "Error :" + ex.getMessage(); } } @Override protected void onPostExecute(String msg) { Log.e(TAG, msg); } }.execute(null, null, null); }
From source file:com.example.m.niceproject.service.YahooWeatherService.java
public void refreshWeather(String location) { new AsyncTask<String, Void, Channel>() { @Override/* ww w .j a v a2s. c om*/ protected Channel doInBackground(String[] locations) { String location = locations[0]; Channel channel = new Channel(); String YQL = String.format( "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"%s\")", location); String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL)); try { URL url = new URL(endpoint); URLConnection connection = url.openConnection(); connection.setUseCaches(false); InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } JSONObject data = new JSONObject(result.toString()); JSONObject queryResults = data.optJSONObject("query"); int count = queryResults.optInt("count"); if (count == 0) { error = new LocationWeatherException("No weather information found for " + location); return null; } JSONObject channelJSON = queryResults.optJSONObject("results").optJSONObject("channel"); channel.populate(channelJSON); return channel; } catch (Exception e) { error = e; } return null; } @Override protected void onPostExecute(Channel channel) { if (channel == null && error != null) { listener.serviceFailure(error); } else { listener.serviceSuccess(channel); } } }.execute(location); }
From source file:com.deployd.DeploydObject.java
public void deleteInBackground() { AsyncTask<JSONObject, JSONObject, JSONObject> del = new AsyncTask<JSONObject, JSONObject, JSONObject>() { @Override/*from w w w. j ava 2 s .co m*/ protected JSONObject doInBackground(JSONObject... params) { // TODO Auto-generated method stub try { JSONObject result = Deployd.delete("/" + resource + "/" + DeploydObject.this.getObjectId()); return result; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(JSONObject result) { // TODO Auto-generated method stub super.onPostExecute(result); } }; // del.execute(null); }
From source file:com.example.m.niceproject.service.GoogleMapsGeocodingService.java
public void refreshLocation(Location location) { new AsyncTask<Location, Void, LocationResult>() { @Override//from www .j av a2 s . c o m protected LocationResult doInBackground(Location... locations) { Location location = locations[0]; String endpoint = String.format( "https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&key=%s", location.getLatitude(), location.getLongitude(), API_KEY); try { URL url = new URL(endpoint); URLConnection connection = url.openConnection(); connection.setUseCaches(false); InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } JSONObject data = new JSONObject(result.toString()); JSONArray results = data.optJSONArray("results"); if (results.length() == 0) { error = new ReverseGeolocationException("Could not reverse geocode " + location.getLatitude() + ", " + location.getLongitude()); return null; } LocationResult locationResult = new LocationResult(); locationResult.populate(results.optJSONObject(0)); return locationResult; } catch (Exception e) { error = e; } return null; } @Override protected void onPostExecute(LocationResult location) { if (location == null && error != null) { listener.geocodeFailure(error); } else { listener.geocodeSuccess(location); } } }.execute(location); }
From source file:org.messic.android.util.RestJSONClient.java
/** * Rest POST petition to the server at the url param, sending all the post parameters defiend at formData. This post * return an object (json marshalling) of class defined at clazz parameter. You should register a * {@link RestListener} in order to obtain the returned object, this is because the petition is done in an async * process.// w w w.j av a 2 s .com * * @param url {@link string} URL to attack * @param formData {@link MultiValueMap}<?,?/> map of parameters to send * @param clazz Class<T/> class that you will marshall to a json object * @param rl {@link RestListener} listener to push the object returned */ public static <T> void post(final String url, MultiValueMap<?, ?> formData, final Class<T> clazz, final RestListener<T> rl) { final RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); // Sending multipart/form-data requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request final HttpEntity<MultiValueMap<?, ?>> requestEntity = new HttpEntity<MultiValueMap<?, ?>>(formData, requestHeaders); AsyncTask<Void, Void, Void> at = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, clazz); rl.response(response.getBody()); } catch (Exception e) { rl.fail(e); } return null; } }; at.execute(); }