List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java
/** * ???./*from w ww . ja v a2 s .c o m*/ * * @param deviceId ?ID * @param sessionKey ID * @param listener */ public static void asyncRegisterDiscovery(final String deviceId, final String sessionKey, 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(); HttpPut request = new HttpPut( DISCOVERY_CHANGE_URI + "?deviceId=" + deviceId + "&sessionKey=" + sessionKey); 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.sakisds.icymonitor.activities.ConnectionActivity.java
/** * Registers the application with GCM servers asynchronously. * <p/>//from w ww .j a v a 2s . c o m * Stores the registration id, app versionCode, and expiration time in the * application's shared preferences. */ private void registerBackground() { new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration id=" + regid; setRegistrationId(context, regid); } catch (IOException ex) { } return null; } }.execute(null, null, null); }
From source file:ca.rmen.android.palidamuerte.app.poem.detail.PoemDetailFragment.java
@Override public boolean onOptionsItemSelected(MenuItem item) { Log.v(TAG, "onOptionsItemSelected"); if (item.getItemId() == R.id.action_favorite) { final Activity activity = getActivity(); final View rootView = getView(); new AsyncTask<Void, Void, Void>() { @Override/*from ww w . j a va2 s . c om*/ protected Void doInBackground(Void... params) { // Write the poem favorite field. long poemId = getArguments().getLong(ARG_ITEM_ID); PoemSelection poemSelection = new PoemSelection().id(poemId); PoemCursor cursor = poemSelection.query(activity.getContentResolver()); try { if (cursor.moveToFirst()) { boolean wasFavorite = cursor.getIsFavorite(); boolean isFavorite = !wasFavorite; new PoemContentValues().putIsFavorite(isFavorite).update(activity.getContentResolver(), poemSelection); } } finally { cursor.close(); } return null; } @Override protected void onPostExecute(Void params) { // Reread the poem updateView(activity, rootView); } }.execute(); } else if (item.getItemId() == R.id.action_music) { MusicPlayer.getInstance(getActivity()).toggle(); final Activity activity = getActivity(); mHandler.postDelayed(new Runnable() { @Override public void run() { activity.invalidateOptionsMenu(); } }, 200); } return super.onOptionsItemSelected(item); }
From source file:com.microsoft.windowsazure.messaging.e2etestapp.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_settings: startActivity(new Intent(this, NotificationHubsPreferenceActivity.class)); return true; case R.id.menu_run_tests: if (ApplicationContext.getNotificationHubEndpoint().trim().equals("") || ApplicationContext.getNotificationHubKeyName().trim().equals("") || ApplicationContext.getNotificationHubKeyValue().trim().equals("") || ApplicationContext.getNotificationHubName().trim().equals("")) { startActivity(new Intent(this, NotificationHubsPreferenceActivity.class)); } else {/*from ww w . j a va 2 s . c o m*/ runTests(); } return true; case R.id.menu_check_all: changeCheckAllTests(true); return true; case R.id.menu_uncheck_all: changeCheckAllTests(false); return true; case R.id.menu_reset: refreshTestGroupsAndLog(); return true; case R.id.menu_view_log: AlertDialog.Builder logDialogBuilder = new AlertDialog.Builder(this); logDialogBuilder.setTitle("Log"); final WebView webView = new WebView(this); String logContent = TextUtils.htmlEncode(mLog.toString()).replace("\n", "<br />"); String logHtml = "<html><body><pre>" + logContent + "</pre></body></html>"; webView.loadData(logHtml, "text/html", "utf-8"); logDialogBuilder.setPositiveButton("Copy", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboardManager.setText(mLog.toString()); } }); final String postContent = mLog.toString(); logDialogBuilder.setNeutralButton("Post data", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { String url = ApplicationContext.getLogPostURL(); if (url != null && url.trim() != "") { url = url + "?platform=android"; HttpPost post = new HttpPost(); post.setEntity(new StringEntity(postContent, "utf-8")); post.setURI(new URI(url)); new DefaultHttpClient().execute(post); } } catch (Exception e) { // Wasn't able to post the data. Do nothing } return null; } }.execute(); } }); logDialogBuilder.setView(webView); logDialogBuilder.create().show(); return true; default: return super.onOptionsItemSelected(item); } }
From source file:com.scoreflex.ScoreflexGcmClient.java
private static void registerInBackground(final String senderId, final Context activity) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { public void run() { new AsyncTask<Object, Object, Object>() { @Override/*from www . j a v a2s . c o m*/ protected Object doInBackground(Object... arg0) { String msg = ""; try { String regid = ScoreflexGcmWrapper.register(Scoreflex.getApplicationContext(), senderId); if (regid == null) { return null; } msg = "Device registered, registration ID=" + regid; storeRegistrationId(regid, activity); storeRegistrationIdToScoreflex(regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(Object msg) { } }.execute(null, null, null); } }); }
From source file:ca.mudar.mtlaucasou.LocationFragmentActivity.java
/** * Find the last known location (using a {@link LastLocationFinder}) and * updates the place list accordingly.//from w w w. j av a2 s . c o m * * @param updateWhenLocationChanges Request location updates */ protected void getLocationAndUpdateCursor(boolean updateWhenLocationChanges) { /** * This isn't directly affecting the UI, so put it on a worker thread. */ AsyncTask<Void, Void, Void> findLastLocationTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { /** * Find the last known location, specifying a required accuracy * of within the min distance between updates and a required * latency of the minimum time required between updates. */ Location lastKnownLocation = lastLocationFinder.getLastBestLocation(Const.MAX_DISTANCE, System.currentTimeMillis() - Const.MAX_TIME); if (lastKnownLocation != null) { mAppHelper.setLocation(lastKnownLocation); } return null; } }; findLastLocationTask.execute(); /** * If we have requested location updates, turn them on here. */ toggleUpdatesWhenLocationChanges(updateWhenLocationChanges); }
From source file:me.henrytao.smoothappbarlayoutdemo.activity.BaseActivity.java
private void requestItemsForPurchase(final AsyncCallback<List<PurchaseItem>> callback) { if (mPurchaseItems != null && mPurchaseItems.size() > 0) { if (callback != null) { callback.onSuccess(mPurchaseItems); }/*from w w w . j a va 2 s .com*/ return; } new AsyncTask<IInAppBillingService, Void, AsyncResult<List<PurchaseItem>>>() { @Override protected AsyncResult<List<PurchaseItem>> doInBackground(IInAppBillingService... params) { List<PurchaseItem> result = new ArrayList<>(); Throwable exception = null; IInAppBillingService billingService = params[0]; if (billingService == null) { exception = new Exception("Unknow"); } else { ArrayList<String> skuList = new ArrayList<>(Arrays.asList(DONATE_ITEMS)); Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", skuList); try { Bundle skuDetails = billingService.getSkuDetails(3, getPackageName(), "inapp", querySkus); int response = skuDetails.getInt("RESPONSE_CODE"); if (response == 0) { ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); PurchaseItem purchaseItem; for (String item : responseList) { purchaseItem = new PurchaseItem(new JSONObject(item)); if (purchaseItem.isValid()) { result.add(purchaseItem); } } } } catch (RemoteException e) { e.printStackTrace(); exception = e; } catch (JSONException e) { e.printStackTrace(); exception = e; } } return new AsyncResult<>(result, exception); } @Override protected void onPostExecute(AsyncResult<List<PurchaseItem>> result) { if (!isFinishing() && callback != null) { Throwable error = result.getError(); if (error == null && (result.getResult() == null || result.getResult().size() == 0)) { error = new Exception("Unknow"); } if (error != null) { callback.onError(error); } else { mPurchaseItems = result.getResult(); Collections.sort(mPurchaseItems, new Comparator<PurchaseItem>() { @Override public int compare(PurchaseItem lhs, PurchaseItem rhs) { return (int) ((lhs.getPriceAmountMicros() - rhs.getPriceAmountMicros()) / 1000); } }); callback.onSuccess(mPurchaseItems); } } } }.execute(mBillingService); }
From source file:ca.rmen.android.networkmonitor.app.log.LogActivity.java
/** * Read the data from the DB, export it to an HTML file, and load the HTML file in the WebView. *//*from www .j a v a 2 s .co m*/ private void loadHTMLFile() { Log.v(TAG, "loadHTMLFile"); final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar); progressBar.setVisibility(View.VISIBLE); startRefreshIconAnimation(); AsyncTask<Void, Void, File> asyncTask = new AsyncTask<Void, Void, File>() { @Override protected File doInBackground(Void... params) { Log.v(TAG, "loadHTMLFile:doInBackground"); // Export the DB to the HTML file. HTMLExport htmlExport = new HTMLExport(LogActivity.this, false); int recordCount = NetMonPreferences.getInstance(LogActivity.this).getFilterRecordCount(); return htmlExport.export(recordCount, null); } @SuppressLint("SetJavaScriptEnabled") @Override protected void onPostExecute(File result) { Log.v(TAG, "loadHTMLFile:onPostExecute, result=" + result); if (isFinishing()) { Log.v(TAG, "finishing, ignoring loadHTMLFile result"); return; } if (result == null) { Toast.makeText(LogActivity.this, R.string.error_reading_log, Toast.LENGTH_LONG).show(); return; } // Load the exported HTML file into the WebView. mWebView = (WebView) findViewById(R.id.web_view); // Save our current horizontal scroll position so we can keep our // horizontal position after reloading the page. final int oldScrollX = mWebView.getScrollX(); mWebView.getSettings().setUseWideViewPort(true); mWebView.getSettings().setBuiltInZoomControls(true); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl("file://" + result.getAbsolutePath()); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); Log.v(TAG, "onPageStarted"); // Javascript hack to scroll back to our old X position. // http://stackoverflow.com/questions/6855715/maintain-webview-content-scroll-position-on-orientation-change if (oldScrollX > 0) { String jsScrollX = "javascript:window:scrollTo(" + oldScrollX + " / window.devicePixelRatio,0);"; view.loadUrl(jsScrollX); } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); progressBar.setVisibility(View.GONE); stopRefreshIconAnimation(); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.v(TAG, "url: " + url); // If the user clicked on one of the column names, let's update // the sorting preference (column name, ascending or descending order). if (url.startsWith(HTMLExport.URL_SORT)) { NetMonPreferences prefs = NetMonPreferences.getInstance(LogActivity.this); SortPreferences oldSortPreferences = prefs.getSortPreferences(); // The new column used for sorting will be the one the user tapped on. String newSortColumnName = url.substring(HTMLExport.URL_SORT.length()); SortOrder newSortOrder = oldSortPreferences.sortOrder; // If the user clicked on the column which is already used for sorting, // toggle the sort order between ascending and descending. if (newSortColumnName.equals(oldSortPreferences.sortColumnName)) { if (oldSortPreferences.sortOrder == SortOrder.DESC) newSortOrder = SortOrder.ASC; else newSortOrder = SortOrder.DESC; } // Update the sorting preferences (our shared preference change listener will be notified // and reload the page). prefs.setSortPreferences(new SortPreferences(newSortColumnName, newSortOrder)); return true; } // If the user clicked on the filter icon, start the filter activity for this column. else if (url.startsWith(HTMLExport.URL_FILTER)) { Intent intent = new Intent(LogActivity.this, FilterColumnActivity.class); String columnName = url.substring(HTMLExport.URL_FILTER.length()); intent.putExtra(FilterColumnActivity.EXTRA_COLUMN_NAME, columnName); startActivityForResult(intent, REQUEST_CODE_FILTER_COLUMN); return true; } else { return super.shouldOverrideUrlLoading(view, url); } } }); } }; asyncTask.execute(); }
From source file:com.google.developers.actions.debugger.MainActivity.java
public void askCayley(final String query) { new AsyncTask<Void, Void, String>() { @Override/*from w w w. j av a2s .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 = WordUtils.capitalize(query); 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" + "\n" + "function getIdFor(thing) {\n" + " return g.V(thing).In([\"http://rdf.freebase.com/ns/type.object.name\", \"http://schema.org/name\"]).ToValue()\n" + "}\n" + "\n" + "function getTypeFor(id) {\n" + " return g.V(id).Out(\"a\").ToValue()\n" + "}\n" + "\n" + "function getActionForName(name) {\n" + " var uri = getIdFor(name)\n" + " if (uri == null) {\n" + " return\n" + " }\n" + " var type = getTypeFor(uri)\n" + " var artist_query\n" + " if (type == \"http://rdf.freebase.com/ns/music.genre\") {\n" + " artist_query = g.V(uri).In(\"http://rdf.freebase.com/ns/music.artist.genre\")\n" + " } else {\n" + " artist_query = g.V(uri)\n" + " }\n" + " return getActionForArtists(artist_query)\n" + "}\n" + "\n" + "getActionForName(\"" + queryString + "\").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(MainActivity.this, "No nodes found for " + queryString + " 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; } Intent intent = new Intent(); intent.setAction("android.media.action.MEDIA_PLAY_FROM_SEARCH"); intent.setData(Uri.parse(Utils.convertGSAtoUri(appId))); try { startActivity(intent); } catch (ActivityNotFoundException e) { Utils.showError(MainActivity.this, appId + "Activity not found"); } } }.execute((Void) null); }
From source file:org.starfishrespect.myconsumption.android.ui.AddSensorActivity.java
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_sensor); Toolbar toolbar = getActionBarToolbar(); getSupportActionBar().setTitle(getString(R.string.title_add_sensor)); toolbar.setNavigationIcon(R.drawable.ic_up); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override//from w w w . ja v a2 s. c om public void onClick(View view) { Intent intent = getParentActivityIntent(); startActivity(intent); finish(); } }); spinnerSensorType = (Spinner) findViewById(R.id.spinnerSensorType); editTextSensorName = (EditText) findViewById(R.id.editTextSensorName); layoutSensorSpecificSettings = (LinearLayout) findViewById(R.id.layoutSensorSpecificSettings); buttonCreateSensor = (Button) findViewById(R.id.buttonCreateSensor); if (getIntent().getExtras() != null) { Bundle b = getIntent().getExtras(); if (b.containsKey("edit")) { try { editSensor = SingleInstance.getDatabaseHelper().getSensorDao().queryForId(b.getString("edit")); edit = true; editTextSensorName.setText(editSensor.getName()); sensorTypes = new String[1]; sensorTypes[0] = editSensor.getType(); layoutSensorSpecificSettings.removeAllViews(); selectedSensorType = sensorTypes[0].toLowerCase(); sensorView = SensorViewFactory.makeView(AddSensorActivity.this, selectedSensorType); sensorView.setEditMode(true); layoutSensorSpecificSettings.addView(sensorView); buttonCreateSensor.setText(R.string.button_edit_sensor); } catch (SQLException e) { finish(); } } } spinnerSensorType.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, sensorTypes)); if (!edit) { spinnerSensorType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { layoutSensorSpecificSettings.removeAllViews(); selectedSensorType = sensorTypes[position].toLowerCase(); sensorView = SensorViewFactory.makeView(AddSensorActivity.this, selectedSensorType); layoutSensorSpecificSettings.addView(sensorView); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); buttonCreateSensor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!MiscFunctions.isOnline(AddSensorActivity.this)) { MiscFunctions.makeOfflineDialog(AddSensorActivity.this).show(); return; } if (editTextSensorName.getText().toString().equals("") || !sensorView.areSettingsValid()) { new AlertDialog.Builder(AddSensorActivity.this).setTitle(R.string.dialog_title_error) .setMessage("You must fill all the fields in order to add a sensor !") .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); return; } new AsyncTask<Void, Boolean, Void>() { private ProgressDialog waitingDialog; @Override protected void onPreExecute() { waitingDialog = new ProgressDialog(AddSensorActivity.this); waitingDialog.setTitle(R.string.dialog_title_loading); waitingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); waitingDialog.setMessage( getResources().getString(R.string.dialog_message_loading_creating_sensor)); waitingDialog.show(); } @Override protected Void doInBackground(Void... params) { publishProgress(create()); return null; } @Override protected void onProgressUpdate(Boolean... values) { for (boolean b : values) { if (b) { new AlertDialog.Builder(AddSensorActivity.this) .setTitle(R.string.dialog_title_information) .setMessage(R.string.dialog_message_information_sensor_added) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); setResult(RESULT_OK); Intent intent = new Intent(AddSensorActivity.this, ChartActivity.class); intent.putExtra(Config.EXTRA_FIRST_LAUNCH, true); startActivity(intent); } }) .show(); } else { new AlertDialog.Builder(AddSensorActivity.this) .setTitle(R.string.dialog_title_error) .setMessage(R.string.dialog_message_error_sensor_not_added) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } } } @Override protected void onPostExecute(Void aVoid) { waitingDialog.dismiss(); } }.execute(); } }); } else { buttonCreateSensor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask<Void, Boolean, Void>() { private ProgressDialog waitingDialog; @Override protected void onPreExecute() { waitingDialog = new ProgressDialog(AddSensorActivity.this); waitingDialog.setTitle(R.string.dialog_title_loading); waitingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); waitingDialog.setMessage( getResources().getString(R.string.dialog_message_loading_editing_sensor)); waitingDialog.show(); } @Override protected Void doInBackground(Void... params) { publishProgress(edit()); return null; } @Override protected void onProgressUpdate(Boolean... values) { for (boolean b : values) { if (b) { new AlertDialog.Builder(AddSensorActivity.this) .setTitle(R.string.dialog_title_information) .setMessage(R.string.dialog_message_information_sensor_edited) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); setResult(Activity.RESULT_OK); finish(); } }) .show(); } else { new AlertDialog.Builder(AddSensorActivity.this) .setTitle(R.string.dialog_title_error) .setMessage(R.string.dialog_message_error_sensor_not_added) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } } } @Override protected void onPostExecute(Void aVoid) { waitingDialog.dismiss(); } }.execute(); } }); } }