List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:nmtysh.android.test.speedtest.SpeedTestActivity.java
private void runHttpClient() { final String url = urlEdit.getText().toString(); if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) { list.add("URL error!"); adapter.notifyDataSetChanged();/*w w w.ja va 2 s . com*/ return; } task = new AsyncTask<Void, Integer, Void>() { long startTime; ProgressDialog progress; // ?? @Override protected void onPreExecute() { super.onPreExecute(); progress = new ProgressDialog(SpeedTestActivity.this); progress.setMessage(getString(R.string.progress_message)); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setIndeterminate(false); progress.setCancelable(true); progress.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { task.cancel(true); } }); progress.setMax(10); progress.setProgress(0); progress.show(); startTime = System.currentTimeMillis(); } // ??? @Override protected Void doInBackground(Void... params) { // 10????? for (int i = 0; i < 10; i++) { HttpClient client = new DefaultHttpClient(); InputStreamReader in = null; // BufferedReader br = null; try { HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() < 400) { in = new InputStreamReader(response.getEntity().getContent()); // br = new BufferedReader(in); // while (br.readLine() != null) { long len = 0; while (in.read() != -1) { len++; } Log.i("HttpClient", len + " Bytes"); } } catch (IOException e) { } finally { /* * if (br != null) { try { br.close(); } catch * (IOException e) { } br = null; } */ if (in != null) { try { in.close(); } catch (IOException e) { } in = null; } // ? client.getConnectionManager().shutdown(); client = null; } publishProgress(i + 1); // Dos???????? try { Thread.sleep(1000); } catch (InterruptedException e) { } } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); if (progress == null) { return; } progress.setProgress(values[0]); } // @Override protected void onPostExecute(Void result) { long endTime = System.currentTimeMillis(); // progress.cancel(); progress = null; list.add("HttpClient:" + url + " " + (endTime - startTime) + "msec/10" + " " + (endTime - startTime) / 10 + "msec"); adapter.notifyDataSetChanged(); } @Override protected void onCancelled() { super.onCancelled(); progress.dismiss(); progress = null; } }.execute(); }
From source file:be.evias.cloudLogin.cloudLoginMainActivity.java
/** * First thing when the activity is created is to check if * the connection to the server is UP./*from www. j a v a 2s .c om*/ * If not finish the activity and tell the user. **/ public void checkConnection() { new AsyncTask<String, Void, Intent>() { @Override protected Intent doInBackground(String... params) { Bundle data = new Bundle(); try { ServiceBase service = new ServiceBase(); mIsConnectionUp = service.ping(mContext); } catch (Exception e) { } final Intent res = new Intent(); res.putExtras(data); return res; } @Override protected void onPostExecute(Intent intent) { if (mIsConnectionUp == false) { showMessage(mContext.getString(R.string.error_network), Toast.LENGTH_LONG); setResult(RESULT_OK, intent); finish(); } } }.execute(); }
From source file:org.deviceconnect.android.uiapp.fragment.profile.PhoneProfileFragment.java
private void callPhone(final String number) { (new AsyncTask<Void, Void, DConnectMessage>() { public DConnectMessage doInBackground(final Void... args) { try { URIBuilder builder = new URIBuilder(); builder.setProfile(PhoneProfileConstants.PROFILE_NAME); builder.setAttribute(PhoneProfileConstants.ATTRIBUTE_CALL); builder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId()); builder.addParameter(PhoneProfileConstants.PARAM_PHONE_NUMBER, number); builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken()); HttpResponse response = getDConnectClient().execute(getDefaultHost(), new HttpPost(builder.build())); return (new HttpMessageFactory()).newDConnectMessage(response); } catch (URISyntaxException e) { e.printStackTrace();/*from ww w .j a v a 2s .c o m*/ } 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_phone_result); if (result == null) { tv.setText("failed"); } else { tv.setText(result.toString()); } } }).execute(); }
From source file:com.limewoodmedia.nsdroid.activities.News.java
/** * Loads data from the NS API into the overview panels *//*from ww w. j av a2s. c o m*/ private void loadData() { errorMessage = getResources().getString(R.string.general_error); // Show loading animation final LoadingView loadingView = (LoadingView) findViewById(R.id.loading); LoadingHelper.startLoading(loadingView); new AsyncTask<Void, Void, Boolean>() { StringBuilder html; @Override protected void onPreExecute() { html = new StringBuilder(); } protected Boolean doInBackground(Void... params) { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); HttpGet get = new HttpGet(NEWS_URL); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); xpp.setInput(response.getEntity().getContent(), "UTF-8"); String tagName; while (xpp.next() != XmlPullParser.END_DOCUMENT) { switch (xpp.getEventType()) { case XmlPullParser.START_TAG: tagName = xpp.getName().toLowerCase(); if (tagName.equals("item")) { html.append(parseItem(xpp)); } else { Log.w(TAG, "Unknown rss tag: " + tagName); } break; } } return true; } catch (RuntimeException e) { e.printStackTrace(); errorMessage = e.getMessage(); } catch (XmlPullParserException e) { e.printStackTrace(); errorMessage = e.getMessage(); } catch (ClientProtocolException e) { e.printStackTrace(); errorMessage = e.getMessage(); } catch (IOException e) { e.printStackTrace(); errorMessage = e.getMessage(); } return false; } protected void onPostExecute(Boolean result) { // Remove loading animation LoadingHelper.stopLoading(loadingView); if (result) { webView.getSettings().setUseWideViewPort(false); webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); webView.loadDataWithBaseURL("http://www.nationstates.net", "<link rel='stylesheet' href='/ns_v1422597706.css'>" + "<style>h2 {color: #008000;}</style>" + html.toString(), "text/html", "utf-8", null); } else { Toast.makeText(News.this, errorMessage, Toast.LENGTH_SHORT).show(); } } }.execute(); }
From source file:weavebytes.com.futureerp.activities.LoginActivity.java
public void SendJsonRequest() { new AsyncTask<Void, Void, String>() { @Override// w w w . j a va 2s .c om protected void onPreExecute() { super.onPreExecute(); progress.setMessage("Please Wait.."); progress.setProgressStyle(ProgressDialog.STYLE_SPINNER); progress.setCancelable(true); progress.show(); } @Override protected String doInBackground(Void... params) { if (isOnline()) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Config.URL_LOGIN); List<NameValuePair> nameValuePair = new ArrayList<>(); nameValuePair.add(new BasicNameValuePair("username", username)); nameValuePair.add(new BasicNameValuePair("password", password)); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); } catch (UnsupportedEncodingException e) { return e + ""; } try { HttpResponse response = httpClient.execute(httpPost); //Converting Response To JsonString return ConvertResponse_TO_JSON.entityToString(response.getEntity()); } catch (ClientProtocolException e) { // Log exception e.printStackTrace(); } catch (IOException e) { // Log exception e.printStackTrace(); } return "Bad NetWork"; } else { return "Check Your Connection"; } } @Override protected void onPostExecute(String JsonString) { JSONObject jsonobj = null; progress.dismiss(); try { jsonobj = new JSONObject(JsonString); //Parsing JSON and Checking the error_code (username ot password are correct or not) if (jsonobj.getString("error").equals("0")) { Config.U_ID = jsonobj.getString("user_id"); Intent intent = new Intent(LoginActivity.this, DashBoardActivity.class); startActivity(intent); finish(); } else { Toast.makeText(LoginActivity.this, "Invalid User", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); //toast(e + " "); } } }.execute(); }
From source file:edu.csh.coursebrowser.CourseActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_course); // Show the Up button in the action bar. this.getActionBar().setHomeButtonEnabled(false); map_item = new HashMap<String, Course>(); map = new ArrayList<String>(); Bundle args = this.getIntent().getExtras(); this.setTitle(args.getCharSequence("title")); try {// ww w . java 2s. com JSONObject jso = new JSONObject(args.get("args").toString()); JSONArray jsa = new JSONArray(jso.getString("courses")); ListView lv = (ListView) this.findViewById(R.id.course_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); Course course = new Course(obj.getString("title"), obj.getString("department"), obj.getString("course"), obj.getString("description"), obj.getString("id")); addItem(course); Log.v("Added", course.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 Course course = map_item.get(s); new AsyncTask<String, String, String>() { ProgressDialog p; protected void onPreExecute() { p = new ProgressDialog(CourseActivity.this); p.setTitle("Fetching Info"); p.setMessage("Contacting Server..."); p.setCancelable(false); p.show(); } protected String doInBackground(String... dep) { String params = "action=getSections&course=" + course.id; 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(CourseActivity.this, "IO Error!").show(); return; } try { JSONObject jso = new JSONObject(s); JSONArray jsa = new JSONArray(jso.getString("sections")); } catch (JSONException e) { e.printStackTrace(); new AlertError(CourseActivity.this, "Invalid JSON From Server").show(); p.dismiss(); return; } Intent intent = new Intent(CourseActivity.this, SectionsActivity.class); intent.putExtra("title", course.title); intent.putExtra("id", course.id); intent.putExtra("description", course.description); intent.putExtra("args", s); startActivity(intent); p.dismiss(); } }.execute(course.id); } }); } catch (JSONException e) { // TODO Auto-generated catch block new AlertError(this, "Invalid JSON"); e.printStackTrace(); } }
From source file:com.qiqi8226.http.MainActivity.java
private void onBtnPost() { new AsyncTask<String, String, Void>() { @Override// w ww.j a v a2 s . c o m protected Void doInBackground(String... params) { URL url; try { url = new URL(params[0]); URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); bw.write(""); bw.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = br.readLine()) != null) { publishProgress(line); } br.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://www.baidu.com/"); }
From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java
/** * ??????????.//from www .ja v a2 s . c om * * @param deviceId ?? * @param body ? * @param listener ?? */ public static void asyncNotifyBody(final String deviceId, final String body, final DConnectMessageHandler listener) { AsyncTask<Void, Void, DConnectMessage> task = new AsyncTask<Void, Void, DConnectMessage>() { @Override protected DConnectMessage doInBackground(final Void... params) { try { DConnectClient client = new HttpDConnectClient(); HttpPost request = new HttpPost(NOTIFICATION_URI); request.setEntity( new StringEntity(DConnectMessage.EXTRA_DEVICE_ID + "=" + deviceId + "&body=" + body)); HttpResponse response = client.execute(request); return (new HttpMessageFactory()).newDConnectMessage(response); } catch (IOException e) { return new DConnectResponseMessage(DConnectMessage.RESULT_ERROR); } } @Override protected void onPostExecute(final DConnectMessage message) { if (listener != null) { listener.handleMessage(message); } } }; task.execute(); }
From source file:com.twapime.app.util.AsyncImageLoader.java
/** * @param imageUrl/*from w w w. ja va 2 s . c o m*/ * @param imageCallback * @return */ public Drawable loadDrawable(final String imageUrl, ImageLoaderCallback imageCallback) { Drawable drawable = getDrawableFromCache(imageUrl); // if (drawable != null) { return drawable; } // synchronized (callbacks) { List<ImageLoaderCallback> callbacksList = callbacks.get(imageUrl); // if (callbacksList == null) { callbacksList = new Vector<ImageLoaderCallback>(); callbacks.put(imageUrl, callbacksList); } // callbacksList.add(imageCallback); } // if (urlsBeingDownloaded.contains(imageUrl)) { return null; } // urlsBeingDownloaded.add(imageUrl); // new AsyncTask<String, Void, Drawable>() { @Override protected Drawable doInBackground(String... params) { return loadImageFromUrl(imageUrl); } @Override protected void onPostExecute(Drawable drawable) { if (drawable != null) { addDrawableToCache(imageUrl, drawable); // synchronized (callbacks) { for (ImageLoaderCallback callback : callbacks.get(imageUrl)) { callback.imageLoaded(drawable, imageUrl); } // callbacks.remove(imageUrl); } } // urlsBeingDownloaded.remove(imageUrl); } }.execute(); // return null; }
From source file:com.piusvelte.sonet.core.PhotoUploadService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); if (Sonet.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, (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification);/*from w w w .jav a 2s . com*/ (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, mSonetCrypto.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 = SonetHttpClient .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 = SonetHttpClient.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, (Sonet.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); } } } }