List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:ca.rmen.android.palidamuerte.app.poem.list.PoemListFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Activity activity = getActivity(); new AsyncTask<Void, Void, String>() { @Override/*from ww w .j av a 2s . co m*/ protected String doInBackground(Void... params) { return Poems.getActivityTitle(activity, activity.getIntent()); } @Override protected void onPostExecute(String categoryName) { activity.getActionBar().setTitle(categoryName); } }.execute(); }
From source file:edu.csh.coursebrowser.DepartmentActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_departments); // Show the Up button in the action bar. // getActionBar().setDisplayHomeAsUpEnabled(false); this.getActionBar().setHomeButtonEnabled(true); final Bundle b = this.getIntent().getExtras(); map_item = new HashMap<String, Department>(); map = new ArrayList<String>(); Bundle args = this.getIntent().getExtras(); this.setTitle(args.getCharSequence("from")); try {//w w w . ja va2 s .co m JSONObject jso = new JSONObject(args.get("args").toString()); JSONArray jsa = new JSONArray(jso.getString("departments")); ListView lv = (ListView) this.findViewById(R.id.department_list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map); for (int i = 0; i < jsa.length(); ++i) { String s = jsa.getString(i); JSONObject obj = new JSONObject(s); Department dept = new Department(obj.getString("title"), obj.getString("id"), obj.getString("code")); addItem(dept); Log.v("Added", dept.toString()); } lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { String s = ((TextView) arg1).getText().toString(); final Department department = map_item.get(s); new AsyncTask<String, String, String>() { ProgressDialog p; protected void onPreExecute() { p = new ProgressDialog(DepartmentActivity.this); p.setTitle("Fetching Info"); p.setMessage("Contacting Server..."); p.setCancelable(false); p.show(); } protected String doInBackground(String... dep) { String params = "action=getCourses&department=" + dep[0] + "&quarter=" + b.getString("qCode"); Log.v("Params", params); URL url; String back = ""; try { url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax" + ".php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(params); writer.flush(); String line; BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { Log.v("Back:", line); back += line; } writer.close(); reader.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); p.dismiss(); return null; } return back; } protected void onPostExecute(String s) { if (s == null || s == "") { new AlertError(DepartmentActivity.this, "IO Error!").show(); return; } try { JSONObject jso = new JSONObject(s); JSONArray jsa = new JSONArray(jso.getString("courses")); } catch (JSONException e) { e.printStackTrace(); new AlertError(DepartmentActivity.this, "Invalid JSON From Server").show(); p.dismiss(); return; } Intent intent = new Intent(DepartmentActivity.this, CourseActivity.class); intent.putExtra("title", department.title); intent.putExtra("id", department.id); intent.putExtra("code", department.code); intent.putExtra("args", s); startActivity(intent); p.dismiss(); } }.execute(department.id); } }); } catch (JSONException e) { // TODO Auto-generated catch block new AlertError(this, "Invalid JSON"); e.printStackTrace(); } }
From source file:jacky.song.android.util.net.HttpConnector.java
/** * Connects to an url asynchronisely, and invokes the respHandler when it's done. * /*from www. j a v a 2 s. co m*/ * @param method * @param url * @param params * @param chainType * The ProcessorChain you want to use to deal with the response data * @param errorCallback * Callback when the server response code isn't 200 * @throws IllegalStateException * if the init() method hasn't been called */ public static void asyncConnect(final HttpMethod method, final String url, final Map<String, Object> params, final Class<? extends ProcessorChain> chainType, final Closure<HttpResponse> errorCallback) { checkProperInitialized(); new AsyncTask<Void, Void, HttpResponse>() { @Override protected HttpResponse doInBackground(Void... p) { final HttpResponse[] response = new HttpResponse[1]; syncConnect(method, url, params, chainType, new Closure<HttpResponse>() { @Override public void doWith(HttpResponse data) { response[0] = data; } }); // (response[0] == null) means no error happened, so return the response // The reason why return the response rather than invoke the callback directly is because this method is running in // a separate thread, not in main thread, if the user want to update the UI in the error callback, they have to do // a little more work. return response[0] == null ? null : response[0]; } @Override protected void onPostExecute(HttpResponse result) { if (result != null) // error errorCallback.doWith(result);// call error callback, now it's called in main thread, user can update UI } }.execute((Void) null); }
From source file:com.dtz.plugins.azurehubnotification.AzureHubNotification.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private void unRegisterFromAzureNotificationHub(final CallbackContext callbackContext) { final String senderId = AzureConfig.getSenderId(this.cordova.getActivity()); NotificationsManager.handleNotifications(this.cordova.getActivity(), senderId, NotificationHandler.class); gcm = GoogleCloudMessaging.getInstance(this.cordova.getActivity()); String connectionString = AzureConfig.getEndPoint(this.cordova.getActivity()); String notificationHubPath = AzureConfig.getNotificationHubPath(this.cordova.getActivity()); Log.i(TAG, "Configuration data :senderId : " + senderId + " , notificationHubPath :" + notificationHubPath + " , connectionString : " + connectionString); hub = new NotificationHub(notificationHubPath, connectionString, this.cordova.getActivity()); new AsyncTask() { @Override//from w w w. j a v a 2 s . c o m protected Object doInBackground(Object... params) { try { regid = getRegistrationId(AzureHubNotification.this.cordova.getActivity()); if (!regid.isEmpty()) { gcm.unregister(); hub.unregisterAll(regid); Log.i(TAG, "Unregister for GCM and Azure hub using REG_ID : " + regid); } else { Log.i(TAG, "You can unregister before register"); } } catch (Exception e) { Log.e(TAG, "Error in Unregistering Handle : " + e.getMessage()); return e; } return null; } @Override protected void onPostExecute(Object result) { Log.i(TAG, "Handle unregistered"); super.onPostExecute(result); sendNotificationCallback(callbackContext, "Handle unregistered with Server", PluginResult.Status.OK); } }.execute(null, null, null); }
From source file:com.shafiq.myfeedle.core.PhotoUploadService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); if (Myfeedle.ACTION_UPLOAD.equals(action)) { if (intent.hasExtra(Accounts.TOKEN) && intent.hasExtra(Statuses.MESSAGE) && intent.hasExtra(Widgets.INSTANT_UPLOAD)) { String place = null; if (intent.hasExtra(Splace)) place = intent.getStringExtra(Splace); String tags = null; if (intent.hasExtra(Stags)) tags = intent.getStringExtra(Stags); // upload a photo Notification notification = new Notification(R.drawable.notification, "uploading photo", System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", "uploading", PendingIntent.getActivity(PhotoUploadService.this, 0, (Myfeedle.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification);//from ww w . ja v a 2s .c o m (new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { String response = null; if (params.length > 2) { Log.d(TAG, "upload file: " + params[2]); HttpPost httpPost = new HttpPost(String.format(FACEBOOK_PHOTOS, FACEBOOK_BASE_URL, Saccess_token, mMyfeedleCrypto.Decrypt(params[0]))); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(params[2]); ContentBody fileBody = new FileBody(file); entity.addPart(Ssource, fileBody); HttpClient httpClient = MyfeedleHttpClient .getThreadSafeClient(getApplicationContext()); try { entity.addPart(Smessage, new StringBody(params[1])); if (params[3] != null) entity.addPart(Splace, new StringBody(params[3])); if (params[4] != null) entity.addPart(Stags, new StringBody(params[4])); httpPost.setEntity(entity); response = MyfeedleHttpClient.httpResponse(httpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } return response; } @Override protected void onPostExecute(String response) { // notify photo success String message = getString(response != null ? R.string.success : R.string.failure); Notification notification = new Notification(R.drawable.notification, "photo upload " + message, System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", message, PendingIntent.getActivity(PhotoUploadService.this, 0, (Myfeedle.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification); stopSelfResult(mStartId); } }).execute(intent.getStringExtra(Accounts.TOKEN), intent.getStringExtra(Statuses.MESSAGE), intent.getStringExtra(Widgets.INSTANT_UPLOAD), place, tags); } } } }
From source file:com.is.rest.cache.CacheAwareHttpClient.java
/** * Intercepts all requests sent and run them through the cache policies * @see AsyncHttpClient#sendRequest(org.apache.http.impl.client.DefaultHttpClient, org.apache.http.protocol.HttpContext, org.apache.http.client.methods.HttpUriRequest, String, ResponseHandlerInterface, Context) *///from w ww. j a va2 s .co m @Override @SuppressWarnings("unchecked") protected RequestHandle sendRequest(final DefaultHttpClient client, final HttpContext httpContext, final HttpUriRequest uriRequest, final String contentType, final ResponseHandlerInterface responseHandler, final Context context) { Logger.d("CacheAwareHttpClient.sendRequest"); AsyncTask<Void, Void, Pair<Object, Boolean>> task; if (Callback.class.isAssignableFrom(responseHandler.getClass())) { final Callback<Object> callback = (Callback<Object>) responseHandler; final CacheInfo cacheInfo = callback.getCacheInfo(); callback.setCacheManager(cacheManager); if (callback.getCacheInfo().getKey() == null) { try { callback.getCacheInfo().setKey(uriRequest.getURI().toURL().toString()); } catch (MalformedURLException e) { Logger.e("unchacheable because uri threw : ", e); } } task = new AsyncTask<Void, Void, Pair<Object, Boolean>>() { @Override public Pair<Object, Boolean> doInBackground(Void... params) { Pair<Object, Boolean> cachedResult = null; if (Callback.class.isAssignableFrom(responseHandler.getClass())) { switch (callback.getCacheInfo().getPolicy()) { case ENABLED: try { cachedResult = new Pair<Object, Boolean>( cacheManager.get(cacheInfo.getKey(), cacheInfo), false); } catch (IOException e) { Logger.e("cache error", e); } catch (ClassNotFoundException e) { Logger.e("cache error", e); } break; case NETWORK_ENABLED: try { cachedResult = new Pair<Object, Boolean>( cacheManager.get(cacheInfo.getKey(), cacheInfo), true); } catch (IOException e) { Logger.e("cache error", e); } catch (ClassNotFoundException e) { Logger.e("cache error", e); } break; case LOAD_IF_OFFLINE: if (callback.getContext() == null) { throw new IllegalArgumentException( "Attempt to use LOAD_IF_OFFLINE on a callback with no context provided. Context is required to lookup internet connectivity"); } ConnectivityManager connectivityManager = (ConnectivityManager) callback.getContext() .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected()) { try { cachedResult = new Pair<Object, Boolean>( cacheManager.get(cacheInfo.getKey(), cacheInfo), false); } catch (IOException e) { Logger.e("cache error", e); } catch (ClassNotFoundException e) { Logger.e("cache error", e); } } break; default: break; } } return cachedResult; } @Override public void onPostExecute(Pair<Object, Boolean> result) { if (result != null && result.first != null) { Logger.d("CacheAwareHttpClient.sendRequest.onPostExecute proceeding with cache: " + result); callback.getCacheInfo().setLoadedFromCache(true); callback.onSuccess(HttpStatus.SC_OK, null, null, result.first); if (result.second != null && result.second) { //retry request if necessary even if loaded from cache such as in NETWORK_ENABLED if (Callback.class.isAssignableFrom(responseHandler.getClass())) { Callback<Object> callback = (Callback<Object>) responseHandler; CacheInfo secondCacheInfo = callback.getCacheInfo(); secondCacheInfo.setPolicy(CachePolicy.ENABLED); secondCacheInfo.setLoadedFromCache(false); try { boolean invalidated = cacheManager.invalidate(secondCacheInfo.getKey()); Logger.d(String.format("Key: '%s' invalidated as result of second call: %s", secondCacheInfo.getKey(), invalidated)); } catch (IOException e) { Logger.e("cache error", e); } Logger.d("Sending second cache filling call for " + uriRequest); CacheAwareHttpClient.super.sendRequest(client, httpContext, uriRequest, contentType, responseHandler, context); } } } else { Logger.d("CacheAwareHttpClient.sendRequest.onPostExecute proceeding uncached"); CacheAwareHttpClient.super.sendRequest(client, httpContext, uriRequest, contentType, responseHandler, context); } } }; ExecutionUtils.execute(task); } return new RequestHandle(null); }
From source file:ca.rmen.android.networkmonitor.app.prefs.FilterColumnActivity.java
public void onOk(@SuppressWarnings("UnusedParameters") View v) { Log.v(TAG, "onOk"); // Update the preference for values to filter, for this particular column. // Build a list of all the values the user selected. SparseBooleanArray checkedPositions = mListView.getCheckedItemPositions(); final List<String> selectedValues = new ArrayList<>(mListView.getCount()); for (int i = 0; i < mListView.getCount(); i++) { if (checkedPositions.get(i)) selectedValues.add(((FilterListItem) mListView.getAdapter().getItem(i)).value); }/*w w w . jav a2 s.co m*/ new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // Update the filter preference for this column. String columnName = getIntent().getExtras().getString(EXTRA_COLUMN_NAME); NetMonPreferences.getInstance(FilterColumnActivity.this).setColumnFilterValues(columnName, selectedValues); return null; } @Override protected void onPostExecute(Void result) { setResult(Activity.RESULT_OK); finish(); } }.execute(); }
From source file:net.kourlas.voipms_sms.Billing.java
public void postDonation(final String token, final Activity sourceActivity) { new AsyncTask<Void, Void, Void>() { @Override//from www . ja va 2 s . c o m protected Void doInBackground(Void... params) { try { billingService.consumePurchase(3, sourceActivity.getPackageName(), token); } catch (Exception ignored) { // Do nothing. } return null; } }.execute(); }
From source file:edu.csh.coursebrowser.SchoolActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_course_browser); ListView lv = (ListView) this.findViewById(R.id.schools); this.setTitle("Course Browser"); map_items = new HashMap<String, School>(); map = new ArrayList<String>(); this.sp = getPreferences(MODE_WORLD_READABLE); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map); this.setTitle("Course Browser"); if (!sp.contains("firstRun")) { SharedPreferences.Editor e = sp.edit(); e.putBoolean("firstRun", false); e.commit();//from www .j a va 2 s .com Intent intent = new Intent(SchoolActivity.this, AboutActivity.class); startActivity(intent); } addItem(new School("01", "Saunder's College of Business")); addItem(new School("03", "College of Engineering")); addItem(new School("05", "College of Liberal Arts")); addItem(new School("06", "Applied Science & Technology")); addItem(new School("08", "NTID")); addItem(new School("10", "College of Science")); addItem(new School("11", "Wellness")); addItem(new School("17", "Academic Services")); addItem(new School("20", "Imaging Arts and Sciences")); addItem(new School("30", "Interdisciplinary Studies")); addItem(new School("40", "GCCIS")); addItem(new School("50", "Institute for Sustainability")); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { String s = ((TextView) arg1).getText().toString(); final School school = map_items.get(s); new AsyncTask<String, String, String>() { ProgressDialog p; protected void onPreExecute() { p = new ProgressDialog(SchoolActivity.this); p.setTitle("Fetching Info"); p.setMessage("Contacting Server..."); p.setCancelable(false); p.show(); } protected String doInBackground(String... school) { String params = "action=getDepartments&school=" + school[0] + "&quarter=20123"; Log.v("Params", params); URL url; String back = ""; try { url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(params); writer.flush(); String line; BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { Log.v("Back:", line); back += line; } writer.close(); reader.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } return back; } protected void onPostExecute(String s) { if (s == null || s == "") { new AlertError(SchoolActivity.this, "IO Error!").show(); return; } try { JSONObject jso = new JSONObject(s); JSONArray jsa = new JSONArray(jso.getString("departments")); ArrayList<Department> depts = new ArrayList<Department>(); for (int i = 0; i < jsa.length(); ++i) { JSONObject obj = new JSONObject(jsa.get(i).toString()); depts.add(new Department(obj.getString("title"), obj.getString("id"), obj.getString("code"))); } } catch (JSONException e) { e.printStackTrace(); new AlertError(SchoolActivity.this, "Invalid JSON From Server").show(); p.dismiss(); return; } Intent intent = new Intent(SchoolActivity.this, DepartmentActivity.class); intent.putExtra("from", school.deptName); intent.putExtra("args", s); intent.putExtra("qCode", sp.getString("quarter", "20122")); startActivity(intent); p.dismiss(); } }.execute(school.deptNum); } }); }
From source file:au.id.tmm.anewreader.view.MainActivity.java
/** * Retrieves an Account object by first attempting to retrieve one from a previous session, then * if that fails launching an AuthenticateActivity to retrieve an Account from the user. */// www. ja v a 2 s . co m private void retrieveAccount() { final PreviousAccountInfoFile infoFile = this.getPreviousAccountInfoFile(); new AsyncTask<PreviousAccountInfoFile, Void, Account>() { @Override protected Account doInBackground(PreviousAccountInfoFile... previousAccountInfoFiles) { return previousAccountInfoFiles[0].getPreviousAccount(); } @Override protected void onPostExecute(Account accountFromPreviousSession) { if (accountFromPreviousSession != null) { onHaveAuthenticatedAccount(accountFromPreviousSession); } else { launchAuthenticateActivity(); } } }.execute(infoFile); }