List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:com.perm.DoomPlay.ListVkActivity.java
private void refreshAudios() { asyncTask = new AsyncTask<Void, Void, Void>() { @Override/*from w ww.jav a 2s . c om*/ protected void onPreExecute() { super.onPreExecute(); isLoading = true; linearLoading.setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... params) { try { if (currentAction.equals(actionMyMusic)) { audios = TracksHolder.audiosVk = MainScreenActivity.api.getAudio(Account.account.user_id, null, null, SettingActivity.getPreference("countvkall")); } else if (currentAction.equals(actionMyAlbums)) audios = MainScreenActivity.api.getAudio(null, null, VkAlbumsActivity.albums.get(VkAlbumsActivity.currentAlbum).album_id, SettingActivity.getPreference("countvkall")); } catch (IOException e) { showException(e); cancel(false); } catch (JSONException e) { showException(e); cancel(false); } catch (KException e) { handleKException(e); cancel(false); } return null; } @Override protected void onCancelled() { super.onCancelled(); isLoading = false; linearLoading.setVisibility(View.GONE); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); isLoading = false; linearLoading.setVisibility(View.GONE); if (adapter == null) { adapter = new ListsAdapter(audios, getBaseContext()); listView.setAdapter(adapter); } else { adapter.changeData(audios); } markItem(PlayingService.indexCurrentTrack, false); } }; asyncTask.execute(); }
From source file:ca.ualberta.cmput301.t03.user.EditProfileFragment.java
/** * {@inheritDoc}/*from www.java 2 s . c o m*/ */ @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mNameField = (EditText) getView().findViewById(R.id.profileNameEditText); mCityField = (EditText) getView().findViewById(R.id.profileCityEditText); mEmailField = (EditText) getView().findViewById(R.id.profileEmailEditText); mPhoneField = (EditText) getView().findViewById(R.id.profilePhoneEditText); AsyncTask worker = new AsyncTask() { @Override protected Object doInBackground(Object[] params) { try { model = user.getProfile(); controller = new UserProfileController(model); getActivity().runOnUiThread(new Runnable() { @Override public void run() { populateFields(); } }); } catch (IOException e) { e.printStackTrace(); } catch (ServiceNotAvailableException e) { throw new RuntimeException("App is offline.", e); } return null; } }; worker.execute(); }
From source file:org.deviceconnect.android.uiapp.fragment.profile.ConnectProfileFragment.java
@Override public boolean onPreferenceTreeClick(final PreferenceScreen preferenceScreen, final Preference preference) { boolean result; if (preference.getKey().equals(getString(R.string.key_connection_service_bluetooth_discoverable))) { (new AsyncTask<Void, Integer, Void>() { @Override//w w w .ja v a2s. c om protected Void doInBackground(final Void... params) { URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setProfile(ConnectProfileConstants.PROFILE_NAME); uriBuilder.setInterface(ConnectProfileConstants.INTERFACE_BLUETOOTH); uriBuilder.setAttribute(ConnectProfileConstants.ATTRIBUTE_DISCOVERABLE); uriBuilder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId()); uriBuilder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken()); try { getDConnectClient().execute(new HttpPut(uriBuilder.build())); } catch (IOException e) { mLogger.warning(e.toString()); } catch (URISyntaxException e) { mLogger.warning(e.toString()); } return null; } }).execute(); } result = super.onPreferenceTreeClick(preferenceScreen, preference); return result; }
From source file:com.cssweb.android.quote.QHHQActivity.java
private void loadAllHKStock(final int position) { if (StockInfo.HKINDEX.isEmpty()) openProgress();/*from ww w . j a v a2 s . co m*/ new AsyncTask<Void, Void, Boolean>() { /** * ????? */ @Override protected Boolean doInBackground(Void... arg0) { boolean flag = true; JSONObject quoteData = null; try { if (StockInfo.HKINDEX.isEmpty()) { if (DateTool.isLoadHKStockTime()) {//??9:50? String jsonObject = CssIniFile.loadStockData(QHHQActivity.this, CssIniFile.GetFileName(CssIniFile.HKStockFile)); if (jsonObject != null) { Log.i("==loadAllHKStock9:40?==", ">>>>>>"); quoteData = new JSONObject(jsonObject); JSONObject jMD5 = ConnService.getStockFileMD5(); if (Utils.isHttpStatus(jMD5)) { String serMd5code = jMD5.getJSONObject("data").getString("allstockex"); Log.i("==loadAllHKStock==", "9:10??MD5?:" + quoteData.getString("md5code") + ">>>>>>" + jMD5); if (!quoteData.getString("md5code").equals(serMd5code)) { quoteData = ConnService.getAllHKStock(); } } flag = initAllStock(quoteData, 4); } else { Log.i("==loadAllHKStock9:40???==", ">>>>>>"); quoteData = ConnService.getAllHKStock(); flag = initAllStock(quoteData, 4); } } else { Log.i("==loadAllHKStock9:40???ALLSTOCK==", ">>>>>>"); String jsonObject = CssIniFile.loadStockData(QHHQActivity.this, CssIniFile.GetFileName(CssIniFile.HKStockFile)); if (jsonObject != null) { Log.i("==loadAllHKStock9:40???ALLSTOCK?==", ">>>>>>"); quoteData = new JSONObject(jsonObject); JSONObject jMD5 = ConnService.getStockFileMD5(); if (Utils.isHttpStatus(jMD5)) { String serMd5code = jMD5.getJSONObject("data").getString("allstockex"); Log.i("==loadAllHKStock==", "9:40??MD5?:" + quoteData.getString("md5code") + ">>>>>>" + jMD5); if (!quoteData.getString("md5code").equals(serMd5code)) { quoteData = ConnService.getAllHKStock(); } } flag = initAllStock(quoteData, 3); } else { Log.i("==loadAllHKStock9:40???ALLSTOCK?==", ">>>>>>"); quoteData = ConnService.getAllHKStock(); flag = initAllStock(quoteData, 3); } } } } catch (JSONException e) { flag = Boolean.FALSE; } catch (Exception e) { flag = Boolean.FALSE; } return flag; } /** * ? */ protected void onPostExecute(Boolean result) { hiddenProgress(); if (result != Boolean.TRUE) { toast(R.string.load_data_error); } else { loadAllStock(position); } } }.execute(); }
From source file:be.evias.cloudLogin.FragmentNavigationDrawer.java
public void retrieveAndStoreUserObject() { new AsyncTask<String, Void, Intent>() { @Override/*w ww . j av a 2s . co m*/ protected Intent doInBackground(String... params) { Bundle data = new Bundle(); try { final String accountName = mPrefs.getString("cloudlogin_active_account_name", ""); if (accountName.length() == 0) throw new Exception("No active User Session found on this device."); mCurrentUser = sServerAuthenticate.getUserObject(mContext, accountName); if (mCurrentUser == null) throw new Exception("Could not retrieve User Object (Server Error)."); } catch (Exception e) { Log.d("cloudLogin", "FragmentNavigationDrawer/retrieveAndStoreUserObject: getUserObject error."); e.printStackTrace(); } final Intent res = new Intent(); res.putExtras(data); return res; } @Override protected void onPostExecute(Intent intent) { if (mCurrentUser != null) initializeNavigationAdapter(); else { Toast.makeText(getActivity(), mContext.getString(R.string.error_network), Toast.LENGTH_LONG) .show(); } } }.execute(); }
From source file:org.deviceconnect.android.uiapp.fragment.profile.DeviceOrientationProfileFragment.java
/** * ?./* w w w . java 2s . com*/ */ private void unregisterEvent() { (new AsyncTask<Void, Void, DConnectMessage>() { public DConnectMessage doInBackground(final Void... args) { try { URIBuilder builder = new URIBuilder(); if (isSSL()) { builder.setScheme("https"); } else { builder.setScheme("http"); } builder.setHost(getHost()); builder.setPort(getPort()); builder.setProfile(DeviceOrientationProfileConstants.PROFILE_NAME); builder.setAttribute(DeviceOrientationProfileConstants.ATTRIBUTE_ON_DEVICE_ORIENTATION); builder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId()); builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken()); builder.addParameter(DConnectMessage.EXTRA_SESSION_KEY, getClientId()); HttpEventManager.INSTANCE.unregisterEvent(builder); } catch (IOException e) { e.printStackTrace(); } return null; } }).execute(); }
From source file:com.android.incallui.ContactInfoCache.java
public void maybeInsertCnapInformationIntoCache(Context context, final Call call, final CallerInfo info) { if (mCachedNumberLookupService == null || TextUtils.isEmpty(info.cnapName) || mInfoMap.get(call.getId()) != null) { return;// w w w. j a v a2s. c o m } final Context applicationContext = context.getApplicationContext(); Log.i(TAG, "Found contact with CNAP name - inserting into cache"); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { ContactInfo contactInfo = new ContactInfo(); CachedContactInfo cacheInfo = mCachedNumberLookupService.buildCachedContactInfo(contactInfo); cacheInfo.setSource(CachedContactInfo.SOURCE_TYPE_CNAP, "CNAP", 0); contactInfo.name = info.cnapName; contactInfo.number = call.getNumber(); contactInfo.type = ContactsContract.CommonDataKinds.Phone.TYPE_MAIN; try { final JSONObject contactRows = new JSONObject().put(Phone.CONTENT_ITEM_TYPE, new JSONObject() .put(Phone.NUMBER, contactInfo.number).put(Phone.TYPE, Phone.TYPE_MAIN)); final String jsonString = new JSONObject().put(Contacts.DISPLAY_NAME, contactInfo.name) .put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.STRUCTURED_NAME) .put(Contacts.CONTENT_ITEM_TYPE, contactRows).toString(); cacheInfo.setLookupKey(jsonString); } catch (JSONException e) { Log.w(TAG, "Creation of lookup key failed when caching CNAP information"); } mCachedNumberLookupService.addContact(applicationContext, cacheInfo); return null; } }.execute(); }
From source file:com.mykola.lexinproject.providers.LexinTranslator.java
protected void loadUrl(final String url, final Translation translation, final HttpListener listener) { LogUtils.LOGD(TAG, "loadUrl >> " + url); mTask = new AsyncTask<Void, Void, Boolean>() { @Override// ww w.jav a2s. c o m protected void onPreExecute() { super.onPreExecute(); } @Override protected Boolean doInBackground(Void... params) { LogUtils.LOGD(TAG, "loadUrl >>"); StringBuilder sb = new StringBuilder(); try { HttpGet httpget = new HttpGet(url); HttpResponse response = mHttpClient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } } catch (IOException ex) { LogUtils.LOGE(TAG, "loadUrl", ex); } catch (RuntimeException ex) { LogUtils.LOGE(TAG, "loadUrl", ex); httpget.abort(); } finally { try { instream.close(); entity.consumeContent(); } catch (Exception ex) { LogUtils.LOGE(TAG, "loadUrl", ex); } } } } catch (Exception ex) { LogUtils.LOGE(TAG, "loadUrl", ex); } LogUtils.LOGD(TAG, "loadUrl <<"); return parseHTML(sb.toString(), translation); } @Override protected void onPostExecute(Boolean found) { super.onPostExecute(found); setState(STATE.eStop); if (listener != null) { if (found) { listener.responseHttpGet(translation); } else { listener.responseHttpGetNotFound(translation.getTranslation()); } } mTask = null; } }.execute(); }
From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java
/** Called when the activity is first created. */ @Override// w w w . ja 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.example.week04.GcmIntentService.java
private void getArticleInBackground(final String keyword) { new AsyncTask<Void, Void, Void>() { private String resultMessage = ""; @Override//from w ww. j a va 2 s . com protected Void doInBackground(Void... params) { String serverURL = new Settings().getServerURL(); String URL = serverURL + "getArticle/" + keyword; DefaultHttpClient client = new DefaultHttpClient(); String result; try { // Make connection to server. Log.i("Connection", "Make connection to server"); HttpParams connectionParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(connectionParams, 5000); HttpConnectionParams.setSoTimeout(connectionParams, 5000); HttpGet httpGet = new HttpGet(URL); // Get response and parse entity. Log.i("Connection", "Get response and parse entity."); HttpResponse responsePost = client.execute(httpGet); HttpEntity resEntity = responsePost.getEntity(); // Parse result to string. Log.i("Connection", "Parse result to string."); result = EntityUtils.toString(resEntity); result = result.replaceAll("'|<|"|>", "''"); } catch (Exception e) { e.printStackTrace(); Log.i("Connection", "Some error in server!"); result = ""; } client.getConnectionManager().shutdown(); // Disconnect. if (!result.isEmpty()) { try { JSONArray articleArray = new JSONArray(result); int arrayLength = articleArray.length(); int updatedRow = 0; DBHelper mHelper = new DBHelper(getApplicationContext()); SQLiteDatabase db = mHelper.getWritableDatabase(); for (int i = 0; i < arrayLength; i++) { JSONObject articleObject = articleArray.getJSONObject(i); String title = articleObject.getString("Title"); String link = articleObject.getString("Link"); String date = articleObject.getString("Date"); String news = articleObject.getString("News"); String content = articleObject.getString("Head"); String query = "INSERT INTO ARTICLES(KEYWORD, TITLE, NEWS, DATE, CONTENT, LINK) VALUES('" + keyword + "', '" + title + "', '" + news + "', '" + date + "', '" + content + "', '" + link + "');"; try { updatedRow++; db.execSQL(query); } catch (SQLException e) { updatedRow--; Log.i("SQL inserting", "SQL exception in " + i + "th row : duplicated?"); } } String thisTime = getThisTime(); String query = "UPDATE KEYWORDS SET LASTUPDATE = '" + thisTime + "' WHERE KEYWORD = '" + keyword + "';"; db.execSQL(query); mHelper.close(); if (updatedRow > 0) { resultMessage = "Article loading complete!"; sendNotification( "'" + keyword + "' " + updatedRow + " !"); } else { resultMessage = "Loading complete - No fresh news."; } } catch (JSONException e) { e.printStackTrace(); resultMessage = "Error in article loading - problem in JSONArray?"; } } else { resultMessage = "Error in receiving articles!"; } Log.i("JSON parsing", resultMessage); return null; } }.execute(null, null, null); }