List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:be.evias.cloudLogin.cloudLoginMainActivity.java
@Override public void onNavigationDrawerItemSelected(final int position) { if (position == NAVIGATION_LOGOUT) /* log out mAccount. */ logoutAccount(mAccount);//from www.ja v a 2 s . c o m else { /* open page */ new AsyncTask<String, Void, Intent>() { @Override protected Intent doInBackground(String... params) { Bundle data = new Bundle(); try { SharedPreferences sp = getBaseContext().getSharedPreferences("cloudlogin", Context.MODE_PRIVATE); String name = sp.getString("cloudlogin_active_account_name", ""); mCurrentUser = sServerAuthenticate.getUserObject(getBaseContext(), name); if (mCurrentUser == null) throw new Exception("Could not retrieve User Object (Server Error)."); } catch (Exception e) { Log.d("cloudLogin", "cloudloginMainActivity/onNavigationDrawerItemSelected: getUserObject error."); e.printStackTrace(); } final Intent res = new Intent(); res.putExtras(data); return res; } @Override protected void onPostExecute(Intent intent) { if (mCurrentUser != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, cloudLoginPageFragment.createPage(position, mCurrentUser)) .commit(); } } }.execute(); } }
From source file:com.example.carrie.carrie_test1.scandrug.java
public void geturl() { AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() { @Override/*from w ww . j a v a2 s .c o m*/ protected Void doInBackground(Integer... integers) { String insertUrl = "http://54.65.194.253/Drug/qrcode.php?urlcode=" + urlcode; OkHttpClient client = new OkHttpClient(); Log.d("uuuuuurl", insertUrl); okhttp3.Request request = new okhttp3.Request.Builder().url(insertUrl).build(); Log.d("okhttpurl", "2222"); try { okhttp3.Response response = client.newCall(request).execute(); Log.d("okhttpurl", "1111"); JSONArray array = new JSONArray(response.body().string()); Log.d("okhttpurl", "33333"); JSONObject object = array.getJSONObject(0); Log.d("okhttpurl", "16666"); Log.d("okhttpurl", object.getString("id")); if ((object.getString("id")).equals("nodata")) { Log.d("okht2tp", "4442222"); //normalDialogEvent(); } else { Log.d("nodata", "noooooooo"); } Log.d("searchtest", array.toString()); for (int i = 0; i < array.length(); i++) { object = array.getJSONObject(i); mydata = new MyData(object.getInt("id"), object.getString("chineseName"), object.getString("image"), object.getString("indication"), object.getString("englishName"), object.getString("licenseNumber"), object.getString("category"), object.getString("component"), object.getString("maker_Country"), object.getString("applicant"), object.getString("maker_Name"), object.getString("QRCode")); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { Intent it = new Intent(scandrug.this, FourthActivity.class); Log.d("customadapter2", "2"); Bundle bundle = new Bundle(); Log.d("customadapter2", "3"); bundle.putInt("id", mydata.getId()); Log.d("customadapter2", "4"); bundle.putString("image", mydata.getImage_link()); bundle.putString("chineseName", mydata.getChineseName()); bundle.putString("indication", mydata.getIndication()); bundle.putString("englishName", mydata.getEnglishName()); bundle.putString("licenseNumber", mydata.getLicenseNumber()); bundle.putString("category", mydata.getCategory()); bundle.putString("component", mydata.getComponent()); bundle.putString("maker_Country", mydata.getMaker_Country()); bundle.putString("applicant", mydata.getApplicant()); bundle.putString("maker_Name", mydata.getMaker_Name()); Log.d("customadapter2", "5"); it.putExtras(bundle); startActivity(it); Log.d("customadapter2", "6"); } }; task.execute(); }
From source file:ca.rmen.android.networkmonitor.app.prefs.SelectFieldsActivity.java
public void onOk(@SuppressWarnings("UnusedParameters") View v) { Log.v(TAG, "onOk"); SparseBooleanArray checkedPositions = mListView.getCheckedItemPositions(); String[] dbColumns = NetMonColumns.getColumnNames(this); final List<String> selectedColumns = new ArrayList<>(dbColumns.length); for (int i = 0; i < dbColumns.length; i++) { if (checkedPositions.get(i)) selectedColumns.add(dbColumns[i]); }// w w w .j a v a 2 s . c o m new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { NetMonPreferences.getInstance(SelectFieldsActivity.this).setSelectedColumns(selectedColumns); return null; } @Override protected void onPostExecute(Void result) { setResult(Activity.RESULT_OK); finish(); } }.execute(); }
From source file:moe.minori.androidoauthtutorialproject.MainActivity.java
/** * Called when button is pressed - calling method's name is defined by layout XML, and must have View param. * * @param v/*w w w . ja v a2 s . c o m*/ */ public void onClick(View v) { if (v.getId() == R.id.getTokensViaOAuthButton) // First button, get Access Token & Refresh Token via Chrome Custom Tab { // In order to use Chrome Custom Tab, phone must have modern Chrome for Android installed // We will use Support Library to avoid using AIDL interface CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build(); // Since some API requires user to use Custom Tabs, we will not provide failback to webview - notice null param. CustomTabActivityHelper customTabActivityHelper = new CustomTabActivityHelper(); // Implicit grant flow request URL params variable - since we don't have web server. ArrayList<Pair<String, String>> urlParams = new ArrayList<>(); urlParams.add(new Pair<>("client_id", Constants.clientId)); urlParams.add(new Pair<>("response_type", "token")); urlParams.add(new Pair<>("scope", "profile")); urlParams.add(new Pair<>("redirect_uri", "http://kawaii.na.minori.ga/fitbitDuctTapeParser.html")); urlParams.add(new Pair<>("prompt", "consent")); CustomTabActivityHelper.openCustomTab(this, customTabsIntent, Uri.parse(RESTRequestParamUtil.paramURLfier(Constants.authURL, urlParams)), null); } else if (v.getId() == R.id.accessApiButton) // Second button, Access to API with Access Token { // Since we are dealing with network methods, we will use AsyncTask. new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { // this block will not be executed in UI thread // try simple API request - profile reading // for API request, we need access token and HTTP GET request String result = null; try { HttpClient httpClient = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(Constants.accessEndpointURL)); // add authorization params - BASIC request.setHeader("Authorization", "Bearer " + accessToken); HttpResponse response = httpClient.execute(request); result = StreamUtil.convertStreamToString(response.getEntity().getContent()); } catch (URISyntaxException | IOException e) { e.printStackTrace(); } accessResult = result; return result; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); // this block will be executed in UI thread // from onResume() EditText accessResultEditText = (EditText) findViewById(R.id.accessResultEditText); if (accessResult != null) accessResultEditText.setText(accessResult); } }.execute(); } }
From source file:ca.ualberta.cmput301.t03.trading.TradeOfferHistoryFragment.java
/** * Sets up adapters for view elements representing trades *//*from w ww .j ava 2 s . com*/ private void setupListView(Context context) { if (context == null) { //we probably got killed, so just return return; } adapter = new TradesAdapter<>(context, model); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Trade selected = (Trade) (parent.getItemAtPosition(position)); final UUID tradeUUID = selected.getTradeUUID(); if (PrimaryUser.getInstance().getUsername().equals(selected.getOwner().getUsername())) { AsyncTask worker = new AsyncTask() { @Override protected Object doInBackground(Object[] params) { try { selected.setHasBeenSeen(true); selected.commitChanges(); } catch (ServiceNotAvailableException e) { // do nothing here } return null; } }; worker.execute(); } Intent intent = new Intent(getContext(), TradeOfferReviewActivity.class); intent.putExtra("TRADE_UUID", tradeUUID); startActivity(intent); } }); }
From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.services.AuthClientService.java
public void checkAccountOnResume() { new AsyncTask<Void, Void, Void>() { @Override/* w ww.j a v a2s . c o m*/ protected Void doInBackground(Void... params) { AccountReadInfoResponse result; try { result = new AuthClientService(context) .checkAccount(Preferences.getAccountId(context.getApplicationContext())); } catch (Exception e) { log.error("Cannot check account", e); return null; } Preferences.setAccountName(context.getApplicationContext(), result.getName()); Preferences.setUserAutoRegister(context.getApplicationContext(), result.getUserAutoregister()); Preferences.setGroupAutoRegister(context.getApplicationContext(), result.getGroupAutoregister()); return null; } }.execute(); }
From source file:com.crenativelabs.signchat.gcm.GcmManager.java
/** * Registers the application with GCM servers asynchronously. * <p>/*from www . j a v a2 s . c o m*/ * Stores the registration ID and the app versionCode in the application's shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(mContext); } regid = gcm.register(GCM_SENDER_ID); msg = "Device registered, registration ID=" + regid; // For this demo: we don't need to send it because the // device will send // upstream messages to a server that echo back the message // using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(mContext, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { Log.i(TAG, "onPostExecute: regId = " + regid); // You should send the registration ID to your server over // HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); } }.execute(null, null, null); }
From source file:com.paymaya.sdk.android.checkout.PayMayaCheckoutActivity.java
private void requestCreateCheckout() { new AsyncTask<Void, Void, Response>() { @Override/*from www . j a va2 s . c o m*/ protected Response doInBackground(Void... voids) { try { Request request = new Request(Request.Method.POST, PayMayaConfig.getEnvironment() == PayMayaConfig.ENVIRONMENT_PRODUCTION ? BuildConfig.API_CHECKOUT_ENDPOINT_PRODUCTION : BuildConfig.API_CHECKOUT_ENDPOINT_SANDBOX); byte[] body = JSONUtils.toJSON(mCheckout).toString().getBytes(); request.setBody(body); String key = mClientKey + ":"; String authorization = Base64.encodeToString(key.getBytes(), Base64.DEFAULT); Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("Authorization", "Basic " + authorization); headers.put("Content-Length", Integer.toString(body.length)); request.setHeaders(headers); AndroidClient androidClient = new AndroidClient(); return androidClient.call(request); } catch (JSONException e) { return new Response(-1, ""); } } @Override protected void onPostExecute(Response response) { if (response.getCode() == 200) { try { JSONObject responseBody = new JSONObject(response.getResponse()); mSessionRedirectUrl = responseBody.getString("redirectUrl"); String[] redirectUrlParts = mSessionRedirectUrl.split("\\?"); mSessionCheckoutId = redirectUrlParts[redirectUrlParts.length - 1]; if (Build.MANUFACTURER.toLowerCase().contains("samsung")) { mSessionRedirectUrl += "&cssfix=true"; } loadUrl(mSessionRedirectUrl); } catch (JSONException e) { finishFailure(e.getMessage()); } } else { finishFailure(response.getResponse()); } } }.execute(); }
From source file:it.mb.whatshare.SendToGCMActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tracker = GoogleAnalytics.getInstance(this).getDefaultTracker(); if ("".equals(registrationID)) { if (!Utils.isConnectedToTheInternet(this)) { Dialogs.noInternetConnection(this, R.string.no_internet_sending, true); } else {/* w ww. jav a2 s.c o m*/ GCMIntentService.registerWithGCM(this); new AsyncTask<Void, Void, Void>() { private ProgressDialog dialog; /* * (non-Javadoc) * * @see android.os.AsyncTask#onPreExecute() */ @Override protected void onPreExecute() { dialog = ProgressDialog.show(SendToGCMActivity.this, getResources().getString(R.string.please_wait), getResources().getString(R.string.wait_registration)); } @Override protected Void doInBackground(Void... params) { try { registrationID = GCMIntentService.getRegistrationID(); } catch (CantRegisterWithGCMException e) { registrationError = e.getMessageID(); } return null; } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(Void result) { super.onPostExecute(result); dialog.dismiss(); if (registrationError != -1) { Dialogs.onRegistrationError(registrationError, SendToGCMActivity.this, true); } else { onNewIntent(getIntent()); } } }.execute(); } } }
From source file:android_network.hetnet.vpn_service.AdapterAccess.java
@Override public void bindView(final View view, final Context context, final Cursor cursor) { // Get values final long id = cursor.getLong(colID); final int version = cursor.getInt(colVersion); final int protocol = cursor.getInt(colProtocol); final String daddr = cursor.getString(colDaddr); final int dport = cursor.getInt(colDPort); long time = cursor.getLong(colTime); int allowed = cursor.getInt(colAllowed); int block = cursor.getInt(colBlock); long sent = cursor.isNull(colSent) ? -1 : cursor.getLong(colSent); long received = cursor.isNull(colReceived) ? -1 : cursor.getLong(colReceived); int connections = cursor.isNull(colConnections) ? -1 : cursor.getInt(colConnections); // Get views//from www . jav a 2 s.c om TextView tvTime = (TextView) view.findViewById(R.id.tvTime); ImageView ivBlock = (ImageView) view.findViewById(R.id.ivBlock); final TextView tvDest = (TextView) view.findViewById(R.id.tvDest); LinearLayout llTraffic = (LinearLayout) view.findViewById(R.id.llTraffic); TextView tvConnections = (TextView) view.findViewById(R.id.tvConnections); TextView tvTraffic = (TextView) view.findViewById(R.id.tvTraffic); // Set values tvTime.setText(new SimpleDateFormat("dd HH:mm").format(time)); if (block < 0) ivBlock.setImageDrawable(null); else { ivBlock.setImageResource(block > 0 ? R.drawable.host_blocked : R.drawable.host_allowed); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(ivBlock.getDrawable()); DrawableCompat.setTint(wrap, block > 0 ? colorOff : colorOn); } } tvDest.setText( Util.getProtocolName(protocol, version, true) + " " + daddr + (dport > 0 ? "/" + dport : "")); if (Util.isNumericAddress(daddr)) new AsyncTask<String, Object, String>() { @Override protected void onPreExecute() { ViewCompat.setHasTransientState(tvDest, true); } @Override protected String doInBackground(String... args) { try { return InetAddress.getByName(args[0]).getHostName(); } catch (UnknownHostException ignored) { return args[0]; } } @Override protected void onPostExecute(String addr) { tvDest.setText(Util.getProtocolName(protocol, version, true) + " >" + addr + (dport > 0 ? "/" + dport : "")); ViewCompat.setHasTransientState(tvDest, false); } }.execute(daddr); if (allowed < 0) tvDest.setTextColor(colorText); else if (allowed > 0) tvDest.setTextColor(colorOn); else tvDest.setTextColor(colorOff); llTraffic.setVisibility(connections > 0 || sent > 0 || received > 0 ? View.VISIBLE : View.GONE); if (connections > 0) tvConnections.setText(context.getString(R.string.msg_count, connections)); if (sent > 1024 * 1204 * 1024L || received > 1024 * 1024 * 1024L) tvTraffic.setText(context.getString(R.string.msg_gb, (sent > 0 ? sent / (1024 * 1024 * 1024f) : 0), (received > 0 ? received / (1024 * 1024 * 1024f) : 0))); else if (sent > 1204 * 1024L || received > 1024 * 1024L) tvTraffic.setText(context.getString(R.string.msg_mb, (sent > 0 ? sent / (1024 * 1024f) : 0), (received > 0 ? received / (1024 * 1024f) : 0))); else tvTraffic.setText(context.getString(R.string.msg_kb, (sent > 0 ? sent / 1024f : 0), (received > 0 ? received / 1024f : 0))); }