List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:com.google.developers.actions.debugger.MainActivity.java
private void loadActions() { setProgressBarIndeterminateVisibility(true); new AsyncTask<Void, Void, List<ActionData>>() { @Override/*from www.j ava 2 s . c o m*/ protected List<ActionData> doInBackground(Void... voids) { Gson gson = new Gson(); Type listType = new TypeToken<List<ActionData>>() { }.getType(); List<ActionData> actionList = new ArrayList<ActionData>(); try { Reader reader = new InputStreamReader(getResources().openRawResource(R.raw.intents)); actionList = gson.fromJson(reader, listType); } catch (JsonIOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonSyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } mActionList = actionList; return actionList; } @Override protected void onPostExecute(List<ActionData> actions) { setProgressBarIndeterminateVisibility(false); if (actions == null) { return; } mActionsListFragment.setActions(actions); } }.execute((Void) null); }
From source file:org.aerogear.diffsync.android.demo.DiffSyncMainActivity.java
@Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);/* w w w .ja va 2 s. co m*/ clientId = UUID.randomUUID().toString(); documentId = getString(R.string.documentId); name = (TextView) findViewById(R.id.name); profession = (TextView) findViewById(R.id.profession); hobby0 = (TextView) findViewById(R.id.hobby0); hobby1 = (TextView) findViewById(R.id.hobby1); hobby2 = (TextView) findViewById(R.id.hobby2); hobby3 = (TextView) findViewById(R.id.hobby3); content = new Info("Luke Skywalker", "Jedi", "Fighting the Dark Side", "going into Tosche Station to pick up some power converters", "Kissing his sister", "Bulls eyeing Womprats on his T-16"); setFields(content); JsonPatchClientSynchronizer synchronizer = new JsonPatchClientSynchronizer(); ClientInMemoryDataStore<JsonNode, JsonPatchEdit> dataStore = new ClientInMemoryDataStore<JsonNode, JsonPatchEdit>(); ClientSyncEngine<JsonNode, JsonPatchEdit> clientSyncEngine = new ClientSyncEngine<JsonNode, JsonPatchEdit>( synchronizer, dataStore); Log.i("onCreate", "observer :" + this); syncClient = SyncClient.<JsonNode, JsonPatchEdit>forHost(getString(R.string.serverHost)) .port(Integer.parseInt(getString(R.string.serverPort))).syncEngine(clientSyncEngine).observer(this) .build(); new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { try { syncClient.connect(); final ClientDocument<JsonNode> clientDocument = clientDoc(documentId, clientId, JsonUtil.toJsonNode(content)); Log.i("onCreate", "Seed Document:" + clientDocument); syncClient.addDocument(clientDocument); } catch (final InterruptedException e) { e.printStackTrace(); } return null; } }.execute(); final Button sync = (Button) findViewById(R.id.sync); sync.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { dialog = ProgressDialog.show(DiffSyncMainActivity.this, getString(R.string.wait), getString(R.string.syncing), true, false); new AsyncTask<ClientDocument<JsonNode>, Void, String>() { @Override protected String doInBackground(final ClientDocument<JsonNode>... params) { Log.i("doInBackground", "Document:" + params[0]); syncClient.diffAndSend(params[0]); return null; } @Override protected void onPostExecute(final String s) { dialog.dismiss(); } }.execute(clientDoc(documentId, clientId, JsonUtil.toJsonNode(gatherUpdates()))); } }); }
From source file:mc.lib.network.AsyncNetworkHelper.java
public static void getJson(final String url, final OnCompleteListener<JSONObject> listener) { new AsyncTask<Void, Void, JSONObject>() { @Override/*from w ww .j av a2 s .c o m*/ protected JSONObject doInBackground(Void... params) { return NetworkHelper.getJson(url); } @Override protected void onPostExecute(JSONObject res) { super.onPostExecute(res); listener.complete(res); } }.execute((Void) null); }
From source file:com.deployd.DeploydObject.java
public void saveInBackground(final ObjectCreateEventHandler onCreated) { AsyncTask<JSONObject, JSONObject, JSONObject> save = new AsyncTask<JSONObject, JSONObject, JSONObject>() { @Override// w w w. j a v a 2 s . c om protected JSONObject doInBackground(JSONObject... params) { // TODO Auto-generated method stub try { JSONObject result = null; if (DeploydObject.this.has("id")) { result = Deployd.put(params[0], "/" + resource + "/" + DeploydObject.this.getString("id")); // TODO: add code for handling junctions } else { result = Deployd.post(params[0], "/" + resource); } 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 if (result != null) { if (onCreated != null) { try { DeploydObject.this.put("id", result.getString("id")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } onCreated.objectCreated(DeploydObject.this); } } super.onPostExecute(result); } }; save.execute(this); }
From source file:ca.rmen.android.palidamuerte.app.poem.detail.PoemDetailActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_poem_detail); getActionBar().setDisplayShowCustomEnabled(true); getActionBar().setCustomView(R.layout.poem_number); setVolumeControlStream(AudioManager.STREAM_MUSIC); mTextViewPageNumber = (TextView) getActionBar().getCustomView(); ActionBar.setCustomFont(this); mViewPager = (ViewPager) findViewById(R.id.pager); // If this is the first time we open the activity, we will use the poem id provided in the intent. // If we are recreating the activity (because of a device rotation, for example), we will display the poem that the user // had previously swiped to, using the ViewPager. final long poemId; if (savedInstanceState != null) poemId = savedInstanceState.getLong(PoemDetailFragment.ARG_ITEM_ID); else/*from www . j a va 2 s . c o m*/ poemId = getIntent().getLongExtra(PoemDetailFragment.ARG_ITEM_ID, -1); new AsyncTask<Void, Void, PoemPagerAdapter>() { private String mActivityTitle; @Override protected PoemPagerAdapter doInBackground(Void... params) { mActivityTitle = Poems.getActivityTitle(PoemDetailActivity.this, getIntent()); PoemSelection poemSelection = Poems.getPoemSelection(PoemDetailActivity.this, getIntent()); return new PoemPagerAdapter(PoemDetailActivity.this, poemSelection, getSupportFragmentManager()); } @Override protected void onPostExecute(PoemPagerAdapter result) { if (isFinishing()) return; try { mPoemPagerAdapter = result; mViewPager.setAdapter(mPoemPagerAdapter); mViewPager.setOnPageChangeListener(mOnPageChangeListener); findViewById(R.id.activity_loading).setVisibility(View.GONE); int position = mPoemPagerAdapter.getPositionForPoem(poemId); mViewPager.setCurrentItem(position); getActionBar().setTitle(mActivityTitle); String pageNumber = getString(R.string.page_number, position + 1, mPoemPagerAdapter.getCount()); mTextViewPageNumber.setText(pageNumber); invalidateOptionsMenu(); } catch (IllegalStateException e) { // Don't have time to investigate the root cause now //https://groups.google.com/forum/#!topic/android-developers/Zpb8YSzTltA Log.e(TAG, e.getMessage(), e); } } }.execute(); // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); }
From source file:de.ub0r.android.callmeter.ui.prefs.PreferencesPlain.java
private void loadRules() { new AsyncTask<Void, Void, JSONObject>() { @Override/* w w w .ja va 2s. co m*/ protected JSONObject doInBackground(final Void... params) { try { String l; StringBuilder sb = new StringBuilder(); File f = new File(PreferencesPlain.this.getCacheDir(), "ub0rrules.json"); if (f.exists() && f.lastModified() + CACHE_TIMEOUT > System.currentTimeMillis()) { Log.i(TAG, "found cached data: " + f.getAbsolutePath()); BufferedReader r = new BufferedReader(new FileReader(f)); while ((l = r.readLine()) != null) { sb.append(l); } r.close(); } if (sb.length() == 0) { if (f.exists()) { f.delete(); } HttpURLConnection c = (HttpURLConnection) new URL( "http://ub0r.de/android/callmeter/rulesets/rulesets.json").openConnection(); Log.i(TAG, "load new data: " + c.getURL()); BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream())); FileWriter w = new FileWriter(f); while ((l = r.readLine()) != null) { sb.append(l); w.write(l); } r.close(); w.close(); } try { return new JSONObject(sb.toString()); } catch (JSONException e) { Log.e(TAG, "JSON Error", e); Log.e(TAG, "JSON: " + sb.toString()); return null; } } catch (IOException e) { Log.e(TAG, "IOError", e); } return null; } @SuppressWarnings({ "deprecation", "rawtypes" }) @Override protected void onPostExecute(final JSONObject result) { if (result == null) { Toast.makeText(PreferencesPlain.this, R.string.err_export_read, Toast.LENGTH_LONG).show(); return; } PreferenceGroup base = (PreferenceGroup) PreferencesPlain.this.findPreference("import_rules_users"); PreferenceManager pm = base.getPreferenceManager(); // delete old base.removeAll(); base = (PreferenceGroup) PreferencesPlain.this.findPreference("import_rules_base"); // build list ArrayList<String> keys = new ArrayList<String>(result.length()); Iterator it = result.keys(); while (it.hasNext()) { keys.add(it.next().toString()); } Collections.sort(keys); keys.remove("common"); keys.add(0, "common"); OnPreferenceClickListener opcl = new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference preference) { Intent intent = new Intent(PreferencesPlain.this, PreferencesRules.class); intent.putExtra(PreferencesRules.EXTRA_JSON, result.toString()); intent.putExtra(PreferencesRules.EXTRA_COUNTRY, preference.getKey()); PreferencesPlain.this.startActivity(intent); return true; } }; for (String k : keys) { PreferenceScreen p = pm.createPreferenceScreen(PreferencesPlain.this); p.setPersistent(false); p.setKey(k); p.setTitle(k); p.setOnPreferenceClickListener(opcl); base.addPreference(p); } } ; }.execute((Void) null); }
From source file:com.teinproductions.tein.papyrosprogress.UpdateCheckReceiver.java
private void checkProgress() { try {//from w w w .ja v a 2 s . c om // Parse the cache String cache = IOUtils.getFile(context, Constants.MILESTONES_CACHE_FILE); if (cache == null) { // We have nothing to compare the new progress to throw new NullPointerException("There was no saved progress cache"); } oldMilestones = parseMilestones(cache); // Parse web page new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { try { MilestoneLoader.Result file = IOUtils.loadPage(Constants.MILESTONES_URL); if (file.getError() != MilestoneLoader.Result.NO_ERROR) return null; else return file.getStrData(); } catch (Exception e) { return null; } } @Override protected void onPostExecute(String result) { newMilestonesPageLoaded(result); } }.execute(); } catch (Exception ignored) { } }
From source file:org.messic.android.util.RestJSONClient.java
/** * Rest GET 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.//ww w.ja v a 2 s. c o m * * @param url {@link string} URL to attack * @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 get(final String url, 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)); // Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request final HttpEntity<MultiValueMap<?, ?>> requestEntity = new HttpEntity<MultiValueMap<?, ?>>( new LinkedMultiValueMap<String, Object>(), 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.GET, requestEntity, clazz); rl.response(response.getBody()); } catch (Exception e) { rl.fail(e); } return null; } }; at.execute(); }
From source file:net.kourlas.voipms_sms.gcm.Gcm.java
/** * Registers for Google Cloud Messaging. Sends the registration token to the application servers. * * @param activity The activity that initiated the registration. * @param showFeedback If true, shows a dialog at the end of the registration process indicating the success or * failure of the process. * @param force If true, retrieves a new registration token even if one is already stored. *//* w w w . ja va 2s. c om*/ public void registerForGcm(final Activity activity, final boolean showFeedback, boolean force) { if (!preferences.getNotificationsEnabled()) { return; } if (preferences.getDid().equals("")) { // Do not show an error; this method should never be called unless a DID is set return; } if (!checkPlayServices(activity, showFeedback)) { return; } final ProgressDialog progressDialog = new ProgressDialog(activity); if (showFeedback) { progressDialog.setMessage(applicationContext.getString(R.string.notifications_gcm_progress)); progressDialog.setCancelable(false); progressDialog.show(); } final InstanceID instanceIdObj = InstanceID.getInstance(applicationContext); final String instanceId = instanceIdObj.getId(); if (preferences.getGcmToken().equals("") || !instanceId.equals(preferences.getGcmInstanceId()) || force) { new AsyncTask<Boolean, Void, Boolean>() { @Override protected Boolean doInBackground(Boolean... params) { try { String token = instanceIdObj.getToken( applicationContext.getString(R.string.notifications_gcm_sender_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); String registrationBackendUrl = "https://voipmssms-kourlas.rhcloud.com/register?" + "did=" + URLEncoder.encode(preferences.getDid(), "UTF-8") + "&" + "reg_id=" + URLEncoder.encode(token, "UTF-8"); JSONObject result = Utils.getJson(registrationBackendUrl); String status = result.optString("status"); if (status == null || !status.equals("success")) { return false; } preferences.setGcmInstanceId(instanceId); preferences.setGcmToken(token); return true; } catch (Exception ex) { return false; } } @Override protected void onPostExecute(Boolean success) { if (showFeedback) { progressDialog.hide(); if (!success) { Utils.showInfoDialog(activity, applicationContext.getResources().getString(R.string.notifications_gcm_fail)); } else { Utils.showInfoDialog(activity, applicationContext.getResources() .getString(R.string.notifications_gcm_success)); } } } }.execute(); } else if (showFeedback) { Utils.showInfoDialog(activity, applicationContext.getResources().getString(R.string.notifications_gcm_success)); } }