List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:com.qiqi8226.http.MainActivity.java
private void onBtnGet() { new AsyncTask<String, String, Void>() { @Override/*from w ww. j a v a2 s . c om*/ protected Void doInBackground(String... params) { try { String tmp = URLEncoder.encode("API", "utf-8"); URL url = new URL(params[0] + tmp); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { publishProgress(line); } br.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(String... values) { tv.append(values[0] + "\n"); } }.execute( "http://fanyi.youdao.com/openapi.do?keyfrom=qiqi8226&key=1401459950&type=data&doctype=xml&version=1.1&q="); }
From source file:org.transdroid.core.seedbox.XirvikSharedSettingsActivity.java
@Override protected void onPreferencesChanged() { new AsyncTask<Void, Void, String>() { @Override/* w w w. ja va 2 s .c om*/ protected String doInBackground(Void... params) { try { // When the shared server settings change, we also have to update the RPC mount point to use SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(XirvikSharedSettingsActivity.this); String server = prefs.getString("seedbox_xirvikshared_server_" + key, null); String user = prefs.getString("seedbox_xirvikshared_user_" + key, null); String pass = prefs.getString("seedbox_xirvikshared_pass_" + key, null); // Retrieve the RPC mount point setting from the server itself DefaultHttpClient httpclient = HttpHelper.createStandardHttpClient(true, user, pass, true, null, HttpHelper.DEFAULT_CONNECTION_TIMEOUT, server, 443); String url = "https://" + server + ":443/browsers_addons/transdroid_autoconf.txt"; HttpResponse request = httpclient.execute(new HttpGet(url)); InputStream stream = request.getEntity().getContent(); String folder = HttpHelper.convertStreamToString(stream).trim(); if (folder.startsWith("<?xml")) { folder = null; } stream.close(); return folder; } catch (Exception e) { Log.d(XirvikSharedSettingsActivity.this, "Could not retrieve the Xirvik shared seedbox RPC mount point setting: " + e.toString()); return null; } } @Override protected void onPostExecute(String result) { storeScgiMountFolder(result); } }.execute(); }
From source file:com.google.android.gcm.demo.logic.DeviceGroupsHelper.java
/** * Execute the HTTP call to create the Device Group in background. * * <code>/*from w w w. ja v a2s. c o m*/ * Content-Type: application/json * Authorization: key=API_KEY * project_id: SENDER_ID * { * "operation": "create", * "notification_key_name": "appUser-Chris", * "registration_ids": ["4", "8", "15", "16", "23", "42"] * } * </code> */ public void asyncCreateGroup(final String senderId, final String apiKey, final String groupName, Bundle members) { final Bundle newMembers = new Bundle(members); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { HttpRequest httpRequest = new HttpRequest(); httpRequest.setHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON); httpRequest.setHeader(HEADER_AUTHORIZATION, "key=" + apiKey); httpRequest.setHeader(HEADER_PROJECT_ID, senderId); JSONObject requestBody = new JSONObject(); requestBody.put("operation", "create"); requestBody.put("notification_key_name", groupName); requestBody.put("registration_ids", new JSONArray(bundleValues2Array(newMembers))); httpRequest.doPost(GCM_GROUPS_ENDPOINT, requestBody.toString()); JSONObject responseBody = new JSONObject(httpRequest.getResponseBody()); if (responseBody.has("error")) { mLogger.log(Log.INFO, "Group creation failed." + "\ngroupName: " + groupName + "\nhttpResponse:" + httpRequest.getResponseBody()); MainActivity.showToast(mContext, R.string.group_toast_group_creation_failed, responseBody.getString("error")); } else { // Store the group in the local storage. DeviceGroup group = new DeviceGroup(); group.notificationKeyName = groupName; group.notificationKey = responseBody.getString("notification_key"); for (String name : newMembers.keySet()) { group.tokens.put(name, newMembers.getString(name)); } Sender sender = mSenders.getSender(senderId); sender.groups.put(group.notificationKeyName, group); mSenders.updateSender(sender); mLogger.log(Log.INFO, "Group creation succeeded." + "\ngroupName: " + group.notificationKeyName + "\ngroupKey: " + group.notificationKey); MainActivity.showToast(mContext, R.string.group_toast_group_creation_succeeded); } } catch (JSONException | IOException e) { mLogger.log(Log.INFO, "Exception while creating a new group" + "\nerror: " + e.getMessage() + "\ngroupName: " + groupName); MainActivity.showToast(mContext, R.string.group_toast_group_creation_failed, e.getMessage()); } return null; } }.execute(); }
From source file:com.google.developers.actions.debugger.CayleyActivity.java
public void sendIntent(View view) { new AsyncTask<Void, Void, String>() { @Override/* w w w. ja v a 2 s.c o m*/ protected String doInBackground(Void... voids) { try { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Utils.CAYLEY_URL); String queryString = mEditText.getText().toString(); queryString = WordUtils.capitalize(queryString) + "\")"; if (mActionType.equals("PLAY_GENRE")) { queryString += ".In(\"http://rdf.freebase.com/ns/music.artist.genre\")"; } String cayleyReq = "function getActionForArtists(artist) {" + "\n" + "return artist.In(\"http://schema.org/sameAs\").Out(\"http://" + "schema.org/potentialAction\").Has(\"a\", \"http://schema.org/" + "ListenAction\").Out(\"http://schema.org/target\")" + "\n" + "}" + "\n" + "function getNameFor(thing) {" + "\n" + "return g.V(thing)." + "In([\"http://rdf.freebase.com/ns/type.object.name\", \"http://" + "schema.org/name\"])" + "\n" + "}" + "\n" + "artists = getNameFor(\"" + queryString + "\n" + "getActionForArtists(artists).All()"; httppost.setEntity(new StringEntity(cayleyReq)); // Execute HTTP Post Request HttpResponse httpResponse = httpclient.execute(httppost); String response = EntityUtils.toString(httpResponse.getEntity()); Gson gson = new Gson(); CayleyResult cayleyResult = gson.fromJson(response, CayleyResult.class); if (cayleyResult.isEmpty()) { Utils.showError(CayleyActivity.this, "No nodes found for the query in Cayley."); return null; } return cayleyResult.getResult(0).getId(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } return null; } @Override protected void onPostExecute(String appId) { setProgressBarIndeterminateVisibility(false); if (appId == null) { return; } mIntent.setData(Uri.parse(Utils.convertGSAtoUri(appId))); try { startActivity(mIntent); } catch (ActivityNotFoundException e) { Utils.showError(CayleyActivity.this, appId + "Activity not found"); } } }.execute((Void) null); }
From source file:fi.iki.dezgeg.matkakorttiwidget.gui.MatkakorttiWidgetApp.java
public static AsyncTask<Void, Void, Void> reportException(final String where, final Throwable e) { e.printStackTrace();/*www .ja v a 2 s.c o m*/ if (prefs.getLong("lastErrorReport", new Date().getTime()) - new Date().getTime() <= MIN_REPORT_INTERVAL_MS) return null; prefs.edit().putLong("lastErrorReport", new Date().getTime()).commit(); return new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); List<NameValuePair> data = new ArrayList<NameValuePair>(); data.add(new BasicNameValuePair("where", where)); data.add(new BasicNameValuePair("backtrace", sw.toString())); if (packageInfo != null) { data.add(new BasicNameValuePair("version", String.format("%s (%s %s)", packageInfo.versionName, packageInfo.versionCode, DEBUG ? "debug" : "release"))); } HttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost(ERROR_REPORT_URL); try { post.setEntity(new UrlEncodedFormEntity(data)); } catch (UnsupportedEncodingException uee) { } try { httpclient.execute(post); System.out.println("Error reported."); } catch (IOException e1) { } } catch (Throwable t) { // ignore } return null; } }.execute(); }
From source file:org.jboss.aerogear.android.cookbook.agreddit.authentication.RedditAuthenticationModule.java
public void login(final String username, final String password, final Callback<HeaderAndBody> callback) { COOKIE_MANAGER = new CookieManager(null, CookiePolicy.ACCEPT_NONE); CookieHandler.setDefault(COOKIE_MANAGER); AsyncTask<Void, Void, HeaderAndBody> task = new AsyncTask<Void, Void, HeaderAndBody>() { private Exception exception; @Override// www . j a v a 2 s .com protected HeaderAndBody doInBackground(Void... params) { HeaderAndBody result; try { HttpProvider provider = new HttpRestProvider(getLoginURL(username)); provider.setDefaultHeader("User-Agent", "AeroGear StoryList Demo /u/secondsun"); provider.setDefaultHeader("Content-Type", "application/x-www-form-urlencoded"); String loginData = buildLoginData(username, password); result = provider.post(loginData); Log.d("Auth", new String(result.getBody())); String json = new String(result.getBody()); JsonObject obj = new JsonParser().parse(json).getAsJsonObject().get("json").getAsJsonObject(); modHash = obj.get("data").getAsJsonObject().get("modhash").getAsString(); authToken = obj.get("data").getAsJsonObject().get("cookie").getAsString(); isLoggedIn = true; } catch (Exception e) { Log.e(RedditAuthenticationModule.class.getSimpleName(), "Error with Login", e); exception = e; return null; } return result; } @Override protected void onPostExecute(HeaderAndBody headerAndBody) { if (exception == null) { callback.onSuccess(headerAndBody); } else { callback.onFailure(exception); } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
From source file:org.deviceconnect.android.uiapp.fragment.profile.NotificationProfileFragment.java
/** * ??.// w ww. j a v a2 s. com * @param view ? */ protected void onClickSend(final View view) { mLogger.entering(getClass().getName(), "onClickSend", view); CharSequence body = ((TextView) getView().findViewById(R.id.fragment_notification_service_body)).getText(); (new AsyncTask<String, Integer, DConnectMessage>() { public DConnectMessage doInBackground(final String... args) { if (args == null || args.length == 0) { return new DConnectResponseMessage(DConnectMessage.RESULT_ERROR); } String type = String.valueOf(mSpinner.getSelectedItemPosition()); String body = args[0]; DConnectMessage message = new DConnectResponseMessage(DConnectMessage.RESULT_ERROR); try { URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setProfile(NotificationProfileConstants.PROFILE_NAME); uriBuilder.setAttribute(NotificationProfileConstants.ATTRIBUTE_NOTIFY); uriBuilder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId()); uriBuilder.addParameter(NotificationProfileConstants.PARAM_TYPE, type); uriBuilder.addParameter(NotificationProfileConstants.PARAM_BODY, body); uriBuilder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken()); HttpResponse response = getDConnectClient().execute(getDefaultHost(), new HttpPost(uriBuilder.build())); message = (new HttpMessageFactory()).newDConnectMessage(response); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return message; } }).execute(body.toString()); mLogger.exiting(getClass().getName(), "onClickSend"); }
From source file:au.id.micolous.frogjump.Util.java
public static void updateCheck(final Activity activity) { (new AsyncTask<Void, Void, Boolean>() { @Override/*w w w . j av a2 s . c o m*/ protected Boolean doInBackground(Void... voids) { try { String my_version = Integer.toString(getVersionCode()); URL url = new URL("https://micolous.github.io/frogjump/version.json"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024]; if (is.read(buffer) == 0) { Log.i(TAG, "Error reading update file, 0 bytes"); return false; } JSONObject root = (JSONObject) new JSONTokener(new String(buffer, "US-ASCII")).nextValue(); if (root.has(my_version)) { if (root.getBoolean(my_version)) { // Definitely needs update. Log.i(TAG, "New version required, explicit flag."); return true; } } else { // unlisted version, assume it is old. Log.i(TAG, "New version required, not in list."); return true; } } } catch (Exception ex) { Log.e(TAG, "Error getting update info", ex); } return false; } @Override protected void onPostExecute(Boolean needsUpdate) { if (needsUpdate) newVersionAlert(activity); } }).execute(); }
From source file:com.playcez.GooglePlus.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = getIntent(); if (intent == null || !intent.hasExtra("token")) { AuthUtils.refreshAuthToken(this); return;/*from w ww . j a v a 2 s . co m*/ } setContentView(R.layout.activity_list); mListView = (ListView) findViewById(R.id.activityList); loginProgress = ProgressDialog.show(GooglePlus.this, "Please wait", "Autheticating...", true); AsyncTask<String, Void, List<Activity>> task = new AsyncTask<String, Void, List<Activity>>() { @Override protected List<Activity> doInBackground(String... params) { try { plus = new PlusWrap(GooglePlus.this).get(); Person mePerson = plus.people().get("me").execute(); Log.d(TAG, "ID:\t" + mePerson.getId()); Log.d(TAG, "Display Name:\t" + mePerson.getDisplayName()); Log.d(TAG, "Image URL:\t" + mePerson.getImage().getUrl()); Log.d(TAG, "Profile URL:\t" + mePerson.getUrl()); final String TOKEN = "access_token"; SharedPreferences myData = getSharedPreferences("myData", MODE_PRIVATE); Editor edit = myData.edit(); edit.putString(TOKEN, "access_token"); edit.putString("uid", mePerson.getId()); edit.commit(); Log.d(TAG, "hererre"); String placesLived = ""; String name = ""; String json = ""; JSONArray obj = null; try { name = mePerson.getDisplayName().toString(); placesLived = mePerson.getPlacesLived().toString(); List<PersonPlacesLived> object = mePerson.getPlacesLived(); json = object.toString(); obj = new JSONArray(json); json = obj.toString(); } catch (Exception e) { e.printStackTrace(); } final SharedPreferences settings = getSharedPreferences(AuthUtils.PREFS_NAME, 0); final String account_name = settings.getString(AuthUtils.PREF_ACCOUNT_NAME, ""); final String accessToken = settings.getString("accessToken", null); sendToServer("https://playcez.com/api_getUID.php", name, mePerson.getBirthday(), mePerson.getId(), mePerson.getCurrentLocation(), obj, mePerson.getGender(), accessToken, account_name); return plus.activities().list("me", "public").execute().getItems(); } catch (IOException e) { loginProgress.dismiss(); Toast.makeText(getApplicationContext(), "Check your network connection!", Toast.LENGTH_LONG) .show(); Log.e(TAG, "Unable to list recommended people for user: " + params[0], e); } return null; } @Override protected void onPostExecute(List<Activity> feed) { if (feed != null) { Log.d(TAG, feed + ""); SharedPreferences data = getSharedPreferences("myData", MODE_PRIVATE); boolean showTut = data.getBoolean("showTut", true); Editor myEdit = data.edit(); myEdit.putBoolean("showTut", false); myEdit.commit(); if (showTut) { startActivity(new Intent(getApplicationContext(), Tutorial3.class)); } else { startActivity(new Intent(getApplicationContext(), Start_Menu.class)); } finish(); } else { } } }; task.execute("me"); }
From source file:mc.lib.network.AsyncNetworkHelper.java
public static void getXml(final String url, final OnCompleteListener<Document> listener) { new AsyncTask<Void, Void, Document>() { @Override//from ww w. ja va 2s. c o m protected Document doInBackground(Void... params) { return NetworkHelper.getXml(url); } @Override protected void onPostExecute(Document res) { super.onPostExecute(res); listener.complete(res); } }.execute((Void) null); }