List of usage examples for android.os AsyncTask execute
@MainThread public static void execute(Runnable runnable)
From source file:apps.junkuvo.alertapptowalksafely.MainActivity.java
@Override public void onNewIntent(Intent intent) { if (intent == null || intent.getData() == null || !intent.getData().toString().startsWith(mCallbackURL)) { return;//w w w .j a v a 2 s .co m } String verifier = intent.getData().getQueryParameter("oauth_verifier"); AsyncTask<String, Void, AccessToken> task = new AsyncTask<String, Void, AccessToken>() { @Override protected AccessToken doInBackground(String... params) { try { return mTwitter.getOAuthAccessToken(mRequestToken, params[0]); } catch (TwitterException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(AccessToken accessToken) { if (accessToken != null) { Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.twitter_auth_succeed), Toast.LENGTH_LONG) .show(); TwitterUtility.storeAccessToken(getApplicationContext(), accessToken); } else { Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.twitter_auth_fail), Toast.LENGTH_LONG) .show(); } } }; task.execute(verifier); }
From source file:jp.mixi.android.sdk.MixiContainerImpl.java
@Override public void showDialog(final Context context, String action, Map<String, String> parameters, final CallbackListener listener, final boolean isCancelable) { Uri uri = Uri.parse(Constants.GRAPH_BASE_URL); android.net.Uri.Builder builder = uri.buildUpon(); builder.appendEncodedPath("dialog" + action); for (Entry<String, String> param : parameters.entrySet()) { builder.appendQueryParameter(param.getKey(), param.getValue()); }/* w w w . j a v a2s.co m*/ final String url = builder.build().toString(); AsyncTask<String, Void, Void> tasc = new AsyncTask<String, Void, Void>() { private Exception e; @Override protected Void doInBackground(String... params) { try { refreshToken(); } catch (RemoteException e) { this.e = e; } catch (ApiException e) { this.e = e; } return null; } @Override protected void onPostExecute(Void res) { if (e == null) { HashMap<String, String> map = new HashMap<String, String>(); map.put("oauth_token", getAccessToken()); new MixiDialog(context, url, map, listener, isCancelable).show(); } else { Log.v(TAG, "refresh token error"); listener.onFatal(new ErrorInfo(e)); } } }; tasc.execute(url); }
From source file:com.google.ytdl.MainActivity.java
private void tryAuthenticate() { if (isFinishing()) { return;/*from ww w . j av a 2 s .co m*/ } mToken = null; setProgressBarIndeterminateVisibility(true); AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { try { // Retrieve a token for the given account and scope. It will // always return either // a non-empty String or throw an exception. mToken = GoogleAuthUtil.getToken(MainActivity.this, mChosenAccountName, "oauth2:" + Scopes.PLUS_PROFILE + " " + YouTubeScopes.YOUTUBE + " " + YouTubeScopes.YOUTUBE_UPLOAD); } catch (GooglePlayServicesAvailabilityException playEx) { GooglePlayServicesUtil.getErrorDialog(playEx.getConnectionStatusCode(), MainActivity.this, REQUEST_GMS_ERROR_DIALOG).show(); } catch (UserRecoverableAuthException userAuthEx) { // Start the user recoverable action using the intent // returned by // getIntent() startActivityForResult(userAuthEx.getIntent(), REQUEST_AUTHENTICATE); return false; } catch (IOException transientEx) { // TODO: backoff Log.e(this.getClass().getSimpleName(), transientEx.getMessage()); } catch (GoogleAuthException authEx) { Log.e(this.getClass().getSimpleName(), authEx.getMessage()); } return true; } @Override protected void onPostExecute(Boolean hideProgressBar) { invalidateOptionsMenu(); if (hideProgressBar) { setProgressBarIndeterminateVisibility(false); } if (mToken != null) { runOnUiThread(new Runnable() { @Override public void run() { saveAccount(); } }); } loadData(); } }; task.execute((Void) null); }
From source file:com.piusvelte.sonet.core.SonetCreatePost.java
protected void getPhoto(Uri uri) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Uri, Void, String> asyncTask = new AsyncTask<Uri, Void, String>() { @Override//ww w. j a v a 2s .c o m protected String doInBackground(Uri... imgUri) { String[] projection = new String[] { MediaStore.Images.Media.DATA }; String path = null; Cursor c = getContentResolver().query(imgUri[0], projection, null, null, null); if ((c != null) && c.moveToFirst()) { path = c.getString(c.getColumnIndex(projection[0])); } else { // some file manages send the path through the uri path = imgUri[0].getPath(); } c.close(); return path; } @Override protected void onPostExecute(String path) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (path != null) setPhoto(path); else (Toast.makeText(SonetCreatePost.this, "error retrieving the photo path", Toast.LENGTH_LONG)) .show(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(uri); }
From source file:com.shafiq.myfeedle.core.MyfeedleCreatePost.java
protected void getPhoto(Uri uri) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Uri, Void, String> asyncTask = new AsyncTask<Uri, Void, String>() { @Override// w w w. j av a 2 s . c o m protected String doInBackground(Uri... imgUri) { String[] projection = new String[] { MediaStore.Images.Media.DATA }; String path = null; Cursor c = getContentResolver().query(imgUri[0], projection, null, null, null); if ((c != null) && c.moveToFirst()) { path = c.getString(c.getColumnIndex(projection[0])); } else { // some file manages send the path through the uri path = imgUri[0].getPath(); } c.close(); return path; } @Override protected void onPostExecute(String path) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (path != null) setPhoto(path); else (Toast.makeText(MyfeedleCreatePost.this, "error retrieving the photo path", Toast.LENGTH_LONG)) .show(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(uri); }
From source file:org.deviceconnect.android.manager.setting.ReqResDebugActivity.java
/** * Http?.//from w w w . j a va 2s . c om * @param request * @param listener Http???? */ private void executeHttpRequest(final HttpUriRequest request, final HttpListener listener) { if (!showProgressDialog()) { return; } AsyncTask<HttpUriRequest, HttpUriRequest, String> task = new AsyncTask<HttpUriRequest, HttpUriRequest, String>() { @Override protected String doInBackground(final HttpUriRequest... params) { if (params == null || params.length < 1) { return "Illegal Parameter."; } HttpUriRequest request = params[0]; DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: try { return EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (ParseException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } case HttpStatus.SC_NOT_FOUND: return "Not found. 404"; default: return "Http connect error."; } } catch (ClientProtocolException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } finally { client.getConnectionManager().shutdown(); } } @Override protected void onPostExecute(final String response) { super.onPostExecute(response); hideProgressDialog(); if (response == null) { return; } StringBuilder sb = new StringBuilder(); sb.append("Request:\n"); sb.append(request.getMethod() + " " + request.getURI() + "\n"); mListAdapter.add(sb.toString()); mListAdapter.add("Response:\n" + response); mListAdapter.notifyDataSetChanged(); if (listener != null) { listener.onReceivedResponse(response); } } }; task.execute(request); }
From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java
/** Called when the activity is first created. */ @Override// w ww. j a v a2s . c o m public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { SocketImplHookFactory.initialize(); } { ProxySelector proxySelector = ProxySelector.getDefault(); Log.d(TAG, "proxySelector=" + proxySelector); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { Log.d(TAG, e.toString()); } List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { Log.d(TAG, " proxy=" + proxy); } } } } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("ExceptionHandler"); layout.addView(tv); Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); { Button btn = new Button(this); btn.setText("upload http AsyncTask"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(0.0.0.0)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { destHost = InetAddress.getByName("0.0.0.0"); if (null != destHost) { try { if (destHost.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + destHost.toString() + " reachable"); } else { Log.d(TAG, "destHost=" + destHost.toString() + " not reachable"); } } catch (IOException e) { } } } catch (UnknownHostException e) { } Log.d(TAG, "destHost=" + destHost); } }); thread.start(); try { thread.join(1000); } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(www.google.com)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { InetAddress dest = InetAddress.getByName("www.google.com"); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); } destHost = dest; } catch (IOException e) { } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp"); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); } destHost = dest; } catch (IOException e) { } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } setContentView(layout); }
From source file:com.github.gorbin.asne.googleplus.GooglePlusSocialNetwork.java
/** * Request {@link com.github.gorbin.asne.core.AccessToken} of Google plus social network that you can get from onRequestAccessTokenCompleteListener * @param onRequestAccessTokenCompleteListener listener for {@link com.github.gorbin.asne.core.AccessToken} request *//*from w w w .ja v a 2s. c o m*/ @Override public void requestAccessToken(OnRequestAccessTokenCompleteListener onRequestAccessTokenCompleteListener) { super.requestAccessToken(onRequestAccessTokenCompleteListener); AsyncTask<Activity, Void, String> task = new AsyncTask<Activity, Void, String>() { @Override protected String doInBackground(Activity... params) { String scope = "oauth2:" + Scopes.PLUS_LOGIN; String token; String error = null; try { token = GoogleAuthUtil.getToken(params[0], Plus.AccountApi.getAccountName(googleApiClient), scope); try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 20000); HttpConnectionParams.setSoTimeout(httpParameters, 20000); HttpClient client = new DefaultHttpClient(httpParameters); String url = "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + token; HttpGet httpGet = new HttpGet(url); HttpResponse response = client.execute(httpGet); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(builder.toString()); JSONObject finalResult = new JSONObject(tokener); error = finalResult.getString("error"); } catch (Exception e) { //Probably shouldn't use Exception E here but there are quite a few //http/io/json exceptions that could occur } if (error != null && error.equals("invalid_token")) { GoogleAuthUtil.clearToken(params[0], token); token = GoogleAuthUtil.getToken(params[0], Plus.AccountApi.getAccountName(googleApiClient), scope); } } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } return token; } @Override protected void onPostExecute(String token) { if (token != null) { ((OnRequestAccessTokenCompleteListener) mLocalListeners.get(REQUEST_ACCESS_TOKEN)) .onRequestAccessTokenComplete(getID(), new AccessToken(token, null)); } else { mLocalListeners.get(REQUEST_ACCESS_TOKEN).onError(getID(), REQUEST_ACCESS_TOKEN, token, null); } } }; task.execute(mActivity); }
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;//ww w. j a va2 s . c om } 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:com.userhook.view.UHMessageView.java
protected void loadMessage(Map<String, Object> params) { if (meta.getDisplayType().equals(UHMessageMeta.TYPE_IMAGE)) { if (meta.getButton1() != null && meta.getButton1().getImage() != null && meta.getButton1().getImage().getUrl() != null) { AsyncTask task = new AsyncTask<Object, Void, Drawable>() { @Override/*from www . j av a 2 s. co m*/ protected Drawable doInBackground(Object... params) { Drawable drawable = null; try { URL url = new URL((String) params[0]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is = conn.getInputStream(); drawable = Drawable.createFromStream(is, "src"); int height = drawable.getIntrinsicHeight(); int width = drawable.getIntrinsicWidth(); drawable.setBounds(0, 0, width, height); } catch (Exception e) { Log.e(UserHook.TAG, "error download message image", e); } return drawable; } @Override protected void onPostExecute(Drawable result) { if (result != null) { // size image to fit inside the view int screenHeight = getResources().getDisplayMetrics().heightPixels; int screenWidth = getResources().getDisplayMetrics().widthPixels; int heightGutter = 40; int widthGutter = 40; int screenSpaceHeight = screenHeight - heightGutter * 2; int screenSpaceWidth = screenWidth - widthGutter * 2; float height = result.getIntrinsicHeight(); float width = result.getIntrinsicWidth(); float aspect = height / width; if (height > screenSpaceHeight) { height = screenHeight; width = height / aspect; } if (width > screenSpaceWidth) { width = screenSpaceWidth; height = width * aspect; } ImageView imageView = new ImageView(getContext()); imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); imageView.setImageDrawable(result); LayoutParams layoutParams = new LayoutParams((int) width, (int) height); layoutParams.addRule(CENTER_IN_PARENT); addView(imageView, layoutParams); // add click handler to image imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (meta.getButton1() != null) { clickedButton(meta.getButton1()); } } }); contentLoaded = true; if (showAfterLoad) { showDialog(); } } } }; task.execute(meta.getButton1().getImage().getUrl()); } } else if (UHMessageTemplate.getInstance().hasTemplate(meta.getDisplayType())) { String html = UHMessageTemplate.getInstance().renderTemplate(meta); loadWebViewContent(html); if (showAfterLoad) { showDialog(); } } else { UHPostAsyncTask asyncTask = new UHPostAsyncTask(params, new UHAsyncTask.UHAsyncTaskListener() { @Override public void onSuccess(String result) { if (result != null) { loadWebViewContent(result); } if (showAfterLoad) { showDialog(); } } }); asyncTask.execute(UserHook.UH_HOST_URL + UH_MESSAGE_PATH); } }