List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:com.github.secondsun.catfactsdemo.networking.CatFactFetcherService.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { new AsyncTask<Intent, Void, Void>() { @Override//ww w . j a va2s . c o m protected Void doInBackground(Intent... params) { if (params != null && params.length > 0) { onHandleIntent(params[0]); } return null; } }.execute(intent); return START_STICKY; }
From source file:mc.lib.network.AsyncNetworkHelper.java
public static void getBitmap(final String url, final OnCompleteListener<Bitmap> listener) { new AsyncTask<Void, Void, Bitmap>() { @Override/* www .ja va2s. co m*/ protected Bitmap doInBackground(Void... params) { return NetworkHelper.getBitmap(url); } @Override protected void onPostExecute(Bitmap res) { super.onPostExecute(res); listener.complete(res); } }.execute((Void) null); }
From source file:com.google.bazel.example.android.activities.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_ping) { new AsyncTask<String, Void, String>() { public static final int READ_TIMEOUT_MS = 5000; public static final int CONNECTION_TIMEOUT_MS = 2000; private String inputStreamToString(InputStream stream) throws IOException { StringBuilder result = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String line;// w w w. ja va 2s . c o m while ((line = reader.readLine()) != null) { result.append(line); } } finally { stream.close(); } return result.toString(); } private HttpURLConnection getConnection(String url) throws IOException { URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT_MS); urlConnection.setReadTimeout(READ_TIMEOUT_MS); return (HttpURLConnection) urlConnection; } @Override protected String doInBackground(String... params) { String url = params[0]; HttpURLConnection connection = null; try { connection = getConnection(url); return new JSONObject(inputStreamToString(connection.getInputStream())) .getString("requested"); } catch (IOException e) { Log.e("background", "IOException", e); return null; } catch (JSONException e) { Log.e("background", "JSONException", e); return null; } finally { if (connection != null) { connection.disconnect(); } } } @Override protected void onPostExecute(String result) { TextView textView = (TextView) findViewById(R.id.text_view); if (result == null) { Toast.makeText(MainActivity.this, getString(R.string.error_sending_request), Toast.LENGTH_LONG).show(); textView.setText("???"); return; } textView.setText(result); } }.execute("http://10.0.2.2:8080/boop"); return true; } return super.onOptionsItemSelected(item); }
From source file:org.starfishrespect.myconsumption.android.tasks.StatValuesUpdater.java
public void refreshDB() { AsyncTask<Void, List, Void> task = new AsyncTask<Void, List, Void>() { @Override//from w ww . ja v a 2s . com protected Void doInBackground(Void... params) { DatabaseHelper db = SingleInstance.getDatabaseHelper(); RestTemplate template = new RestTemplate(); HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser(); ResponseEntity<StatDTO[]> responseEnt; template.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); try { for (SensorData sensor : db.getSensorDao().queryForAll()) { // Stats String url = String.format(SingleInstance.getServerUrl() + "stats/sensor/%s", sensor.getSensorId()); responseEnt = template.exchange(url, HttpMethod.GET, new HttpEntity<>(httpHeaders), StatDTO[].class); StatDTO[] statsArray = responseEnt.getBody(); List<StatDTO> stats = new ArrayList<>(Arrays.asList(statsArray)); ObjectMapper mapper = new ObjectMapper(); try { String json = mapper.writeValueAsString(stats); String key = "stats_" + sensor.getSensorId(); int id = db.getIdForKey(key); KeyValueData valueData = new KeyValueData(key, json); valueData.setId(id); LOGD(TAG, "writing stat in local db: " + json); db.getKeyValueDao().createOrUpdate(valueData); } catch (IOException e) { LOGD(TAG, "Cannot create stats " + stats.toString(), e); } } } catch (SQLException e) { LOGD(TAG, "Cannot create stats ", e); } catch (ResourceAccessException | HttpClientErrorException e) { LOGE(TAG, "Cannot access server ", e); } return null; } @Override protected void onPostExecute(Void aVoid) { if (statUpdateFinishedCallback != null) { statUpdateFinishedCallback.onStatUpdateFinished(); } } }; task.execute(); }
From source file:org.deviceconnect.android.uiapp.fragment.profile.VibrationProfileFragment.java
/** * Vibration???.// w w w .jav a 2 s . co m * @param pattern ? */ private void sendVibration(final CharSequence pattern) { (new AsyncTask<Void, Void, DConnectMessage>() { public DConnectMessage doInBackground(final Void... args) { String p = null; if (pattern != null && pattern.length() > 0) { p = pattern.toString(); } try { URIBuilder builder = new URIBuilder(); builder.setProfile(VibrationProfileConstants.PROFILE_NAME); builder.setAttribute(VibrationProfileConstants.ATTRIBUTE_VIBRATE); builder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId()); if (p != null) { builder.addParameter(VibrationProfileConstants.PARAM_PATTERN, p); } builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken()); HttpResponse response = getDConnectClient().execute(getDefaultHost(), new HttpPut(builder.build())); return (new HttpMessageFactory()).newDConnectMessage(response); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(final DConnectMessage result) { if (getActivity().isFinishing()) { return; } TextView tv = (TextView) getView().findViewById(R.id.fragment_vibration_result); if (result == null) { tv.setText("failed"); } else { tv.setText(result.toString()); } } }).execute(); }
From source file:com.intel.iotkitlib.http.HttpDeleteTask.java
public CloudResponse doAsync(final String url, final HttpTaskHandler taskHandler) { asyncTask = new AsyncTask<String, Void, CloudResponse>() { @Override/*from w w w. j av a 2 s . c om*/ protected CloudResponse doInBackground(String... urls) { return doSync(urls[0]); } protected void onPostExecute(CloudResponse response) { // Done on UI Thread if (response != null && taskHandler != null) { taskHandler.taskResponse(response.code, response.response); } } }; asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url); return new CloudResponse(true, "Successful execute " + url); }
From source file:com.perm.DoomPlay.AddTrackToAlbumDialog.java
@Override public void onResume() { super.onResume(); if (VkAlbumsActivity.albums == null && !isLoading) { new AsyncTask<Void, Void, Void>() { @Override/*from w w w . jav a2 s .c o m*/ protected void onPreExecute() { super.onPreExecute(); linearLoading.setVisibility(View.VISIBLE); isLoading = true; } @Override protected Void doInBackground(Void... params) { try { VkAlbumsActivity.albums = MainScreenActivity.api.getAudioAlbums(Account.account.user_id, null, SettingActivity.getPreference("countvkall")); } catch (IOException e) { isLoading = false; ((AbstractReceiver) getActivity()).showException(e); cancel(false); } catch (JSONException e) { isLoading = false; ((AbstractReceiver) getActivity()).showException(e); cancel(false); } catch (KException e) { isLoading = false; ((AbstractReceiver) getActivity()).handleKException(e); cancel(false); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); listView.setAdapter(new DialogAddAdapter()); linearLoading.setVisibility(View.GONE); isLoading = false; } }.execute(); } else if (!isLoading) { listView.setAdapter(new DialogAddAdapter()); } }
From source file:ca.rmen.android.poetassistant.wotd.Wotd.java
private static void enableWotd(final Context context, final Dictionary dictionary) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { WotdJob.schedule(context);/*from w w w. j a va 2 s .com*/ } else { WotdAlarm.schedule(context); } new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { notifyWotd(context, dictionary); return null; } }.execute(); }
From source file:com.ubikod.urbantag.UrbanTagApplication.java
@Override protected void onApplicationProcessCreate() { Log.i(UrbanTag.TAG, "Launching App !"); /* re initiate wifi message display */ SharedPreferences pref = getApplicationContext().getSharedPreferences("URBAN_TAG_PREF", Context.MODE_PRIVATE); pref.edit().putBoolean("notifiedWifi", false).commit(); /* Fetch tags list */ AsyncTask<Void, Void, List<Tag>> updateTagList = new AsyncTask<Void, Void, List<Tag>>() { @Override/*from ww w . j a va2 s .c o m*/ protected List<Tag> doInBackground(Void... v) { List<Tag> res = new ArrayList<Tag>(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(UrbanTag.API_URL + ACTION_FETCH_TAGS_LIST); Log.i(UrbanTag.TAG, "Fetching tags list on : " + request.getURI().toString()); try { HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String textResponse = ""; String line = ""; while ((line = rd.readLine()) != null) { textResponse += line; } Log.i(UrbanTag.TAG, "Received :" + textResponse); JSONArray jsonTagsArray = new JSONArray(textResponse); for (int i = 0; i < jsonTagsArray.length(); i++) { Tag t = TagManager.createTag(jsonTagsArray.getJSONObject(i)); if (t != null) { res.add(t); } } } catch (ClientProtocolException cpe) { Log.e(UrbanTag.TAG, cpe.getMessage()); } catch (IOException ioe) { Log.e(UrbanTag.TAG, ioe.getMessage()); } catch (JSONException je) { Log.e(UrbanTag.TAG, je.getMessage()); } return res; } @Override protected void onPostExecute(List<Tag> list) { TagManager tagManager = new TagManager(new DatabaseHelper(getApplicationContext(), null)); if (list.size() > 0) tagManager.update(list); } }; updateTagList.execute(); }
From source file:eu.faircode.netguard.ServiceJob.java
@Override public boolean onStartJob(JobParameters params) { Log.i(TAG, "Start job=" + params.getJobId()); new AsyncTask<JobParameters, Object, Object>() { @Override//from www. ja v a 2 s .c o m protected JobParameters doInBackground(JobParameters... params) { Log.i(TAG, "Executing job=" + params[0].getJobId()); HttpsURLConnection urlConnection = null; try { String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); JSONObject json = new JSONObject(); json.put("device", Util.sha256(android_id, "")); json.put("product", Build.DEVICE); json.put("sdk", Build.VERSION.SDK_INT); json.put("country", Locale.getDefault().getCountry()); json.put("netguard", Util.getSelfVersionCode(ServiceJob.this)); try { json.put("store", getPackageManager().getInstallerPackageName(getPackageName())); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); json.put("store", null); } for (String name : params[0].getExtras().keySet()) json.put(name, params[0].getExtras().get(name)); urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection(); urlConnection.setConnectTimeout(cTimeOutMs); urlConnection.setReadTimeout(cTimeOutMs); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Content-type", "application/json"); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(json.toString().getBytes()); // UTF-8 out.flush(); int code = urlConnection.getResponseCode(); if (code != HttpsURLConnection.HTTP_OK) throw new IOException("HTTP " + code); InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream()); Log.i(TAG, "Response=" + Util.readString(isr).toString()); jobFinished(params[0], false); if ("rule".equals(params[0].getExtras().getString("type"))) { SharedPreferences history = getSharedPreferences("history", Context.MODE_PRIVATE); history.edit().putLong(params[0].getExtras().getString("package") + ":submitted", new Date().getTime()).apply(); } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); jobFinished(params[0], true); } finally { if (urlConnection != null) urlConnection.disconnect(); try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } return null; } }.execute(params); return true; }