List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:mr.robotto.MrRobottoEngine.java
/** * Loads the scene asynchronously//from w ww . j a va 2 s . c o m * @param inputStream stream containing the scene */ public void loadSceneTreeAsync(final InputStream inputStream) { AsyncTask<InputStream, Void, MrSceneTree> task = new AsyncTask<InputStream, Void, MrSceneTree>() { @Override protected MrSceneTree doInBackground(InputStream... params) { InputStream inputStream = params[0]; MrMrrLoader loader = new MrMrrLoader(inputStream); try { MrSceneTree tree = loader.parse(); return tree; } catch (IOException e) { cancel(true); e.printStackTrace(); } catch (JSONException e) { cancel(true); e.printStackTrace(); } return null; } @Override protected void onPostExecute(MrSceneTree tree) { super.onPostExecute(tree); if (tree != null) { mSceneTree = tree; mController = mSceneTree.getController(); //mController = new MrSceneTreeController(tree, new MrSceneTreeRender()); initialize(); } } }; task.execute(inputStream); }
From source file:com.gaze.webpaser.StackWidgetService.java
private void getDatafromNetwork() { new AsyncTask<String, Void, String>() { @Override/*from ww w.j a v a 2 s . c o m*/ protected void onPreExecute() { super.onPreExecute(); onStartDataLoading(); } @Override protected String doInBackground(String... params) { ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); try { // Set up HTTP post // HttpClient is more then less deprecated. Need to change // to // URLConnection HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(listUrl); httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); Log.i(LOG_TAG, "finish http"); // Read content & Log inputStream = httpEntity.getContent(); } catch (UnsupportedEncodingException e1) { Log.e("UnsupportedEncodingException", e1.toString()); e1.printStackTrace(); } catch (ClientProtocolException e2) { Log.e("ClientProtocolException", e2.toString()); e2.printStackTrace(); } catch (IllegalStateException e3) { Log.e("IllegalStateException", e3.toString()); e3.printStackTrace(); } catch (IOException e4) { Log.e("IOException", e4.toString()); e4.printStackTrace(); } // Convert response to string using String Builder try { BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); result = sBuilder.toString(); Log.i(LOG_TAG, "finish read stream: " + result); if (!isStreamTheTargetJson(result)) { result = ""; sBuilder.delete(0, sBuilder.length() - 1); } // parse json string here if (!result.isEmpty()) { if (result.startsWith("<html>")) return ""; JSONObject titleJson = new JSONObject(result); JSONArray datajson = titleJson.getJSONArray("data"); JSONArray urlQueue = datajson.getJSONArray(0); for (int i = 0; i < urlQueue.length(); i++) { JSONObject item = urlQueue.getJSONObject(i); String url = item.getString("link"); String introtext = item.getString("introtext"); String title = item.getString("title"); String images = item.getString("images"); String name = item.getString("name"); String time = item.getString("publish_up"); if (url != null) { // addToQueue(GlobalData.baseUrl+'/'+url); addToList(url, introtext, title, images, name, time); } } } } catch (Exception e) { Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString()); } return result; } @Override protected void onPostExecute(String msg) { // mDisplay.append(msg + "\n"); Log.i(LOG_TAG, msg.toString()); onFinishDataLoading(); } }.execute(); }
From source file:at.bitfire.nophonespam.BlacklistActivity.java
protected void deleteSelectedNumbers() { final List<String> numbers = new LinkedList<>(); SparseBooleanArray checked = list.getCheckedItemPositions(); for (int i = checked.size() - 1; i >= 0; i--) if (checked.valueAt(i)) { int position = checked.keyAt(i); numbers.add(adapter.getItem(position).number); }//ww w . ja va 2 s. c o m new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { DbHelper dbHelper = new DbHelper(BlacklistActivity.this); try { SQLiteDatabase db = dbHelper.getWritableDatabase(); for (String number : numbers) db.delete(Number._TABLE, Number.NUMBER + "=?", new String[] { number }); } finally { dbHelper.close(); } getLoaderManager().restartLoader(0, null, BlacklistActivity.this); return null; } }.execute(); }
From source file:ca.ualberta.cmput301.t03.inventory.BrowseInventoryFragment.java
/** * Starts intent for inspecting item//from w w w. j a va 2 s . c om * * @param item */ public void inspectItem(Item item) { AsyncTask<Item, Void, Intent> findItemOwnerAndStartInspectItemActivity = new AsyncTask<Item, Void, Intent>() { @Override protected Intent doInBackground(Item[] items) { Intent intent = new Intent(getContext(), InspectItemView.class); try { for (User friend : PrimaryUser.getInstance().getFriends().getFriends()) { if (friend.getInventory().getItems().containsKey(items[0].getUuid())) { intent.putExtra("user", friend.getUsername()); intent.putExtra("ITEM_UUID", items[0].getUuid().toString()); } } } catch (IOException e) { throw new RuntimeException(e); } catch (ServiceNotAvailableException e) { throw new RuntimeException("App is offline.", e); } return intent; } @Override protected void onPostExecute(Intent i) { super.onPostExecute(i); startActivity(i); } }; findItemOwnerAndStartInspectItemActivity.execute(item); }
From source file:com.RSMSA.policeApp.Adapters.ViewPagerAccidentsDetailsAdapter.java
@Override public Object instantiateItem(ViewGroup container, int position) { inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); android.widget.ScrollView itemView = (ScrollView) inflater.inflate(R.layout.accident_details, container, false);//from w w w.ja v a2 s .c o m final AccidentVehicle accidentVehicle = new AccidentVehicle(); Button addPasenger = (Button) itemView.findViewById(R.id.add_witness); Button next = (Button) itemView.findViewById(R.id.next); final LinearLayout linearLayout = (LinearLayout) itemView.findViewById(R.id.passengers_layout); if (position == tabnames.size() - 1) { next.setVisibility(View.VISIBLE); } else { next.setVisibility(View.GONE); } next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AccidentReportFormActivity.showWitneses(); } }); final EditText fatalEdit = (EditText) itemView.findViewById(R.id.fatal_edit); fatalEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setFatal")); final EditText simpleEdit = (EditText) itemView.findViewById(R.id.simple_edit); simpleEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setSimple")); EditText injuryEdit = (EditText) itemView.findViewById(R.id.injury_edit); injuryEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setSevere_injured")); EditText notInjuredEdit = (EditText) itemView.findViewById(R.id.not_injured_edit); notInjuredEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setOnly_damage")); EditText driverLicenceEdit = (EditText) itemView.findViewById(R.id.license_one); driverLicenceEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setLicence_no") { public void afterFocus(final String text, final EditText editText) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { DHIS2Modal dhis2Modal = new DHIS2Modal("Driver", null, MainOffence.username, MainOffence.password); JSONObject where = new JSONObject(); try { where.put("value", text); } catch (JSONException e) { e.printStackTrace(); } JSONObject driverObject = null; try { JSONArray driver = dhis2Modal.getEvent(where); Log.d(TAG, "returned driver json = " + driver.toString()); driverObject = driver.getJSONObject(0); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { if (driverObject.getString("Driver License Number").equals(text)) { accidentVehicle.setProgram_driver(driverObject.getString("id")); return true; } } catch (JSONException e) { e.printStackTrace(); } catch (NullPointerException e) { Log.e(TAG, "returned json object is null"); } return false; } @Override protected void onPostExecute(Boolean aVoid) { super.onPostExecute(aVoid); if (!aVoid) { editText.setTextColor(context.getResources().getColor(R.color.red)); } else { editText.setTextColor(context.getResources().getColor(R.color.green_500)); } } }.execute(); } }); final EditText alcoholEdit = (EditText) itemView.findViewById(R.id.alcohol_edit); alcoholEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setAlcohol_percentage")); CheckBox drug = (CheckBox) itemView.findViewById(R.id.drug_edit); drug.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { accidentVehicle.setDrug(isChecked); } }); CheckBox phone = (CheckBox) itemView.findViewById(R.id.phone_edit); phone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { accidentVehicle.setPhone_use(isChecked); } }); EditText plateNumber = (EditText) itemView.findViewById(R.id.registration_number_one); plateNumber.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setPlate_number") { public void afterFocus(final String text, final EditText editText) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { DHIS2Modal dhis2Modal = new DHIS2Modal("Vehicle", null, MainOffence.username, MainOffence.password); JSONObject where = new JSONObject(); try { where.put("value", text); } catch (JSONException e) { e.printStackTrace(); } JSONObject vehicleObject = null; try { JSONArray vehiclesArray = dhis2Modal.getEvent(where); Log.d(TAG, "returned vehicle json = " + vehiclesArray.toString()); vehicleObject = vehiclesArray.getJSONObject(0); } catch (JSONException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } try { if (vehicleObject.getString("Vehicle Plate Number").equals(text)) { accidentVehicle.setProgram_vehicle(vehicleObject.getString("id")); return true; } } catch (JSONException e) { e.printStackTrace(); } catch (NullPointerException e) { Log.e(TAG, "returned json object is null"); } return false; } @Override protected void onPostExecute(Boolean aVoid) { super.onPostExecute(aVoid); if (!aVoid) { editText.setTextColor(context.getResources().getColor(R.color.red)); } else { editText.setTextColor(context.getResources().getColor(R.color.light_gray)); } } }.execute(); } }); EditText repairCost = (EditText) itemView.findViewById(R.id.repair_amount_one); repairCost.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setEstimated_repair")); EditText vehicleEdit = (EditText) itemView.findViewById(R.id.vehicle_title_edit); vehicleEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setVehicle")); EditText vehicleTotalEdit = (EditText) itemView.findViewById(R.id.vehicle_total_edit); vehicleTotalEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setVehicle_total")); EditText infastructureEdit = (EditText) itemView.findViewById(R.id.infrastructure_edit); infastructureEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setInfastructure")); EditText costEdit = (EditText) itemView.findViewById(R.id.rescue_cost_edit); costEdit.setOnFocusChangeListener(new CustomeTimeWatcher(accidentVehicle, "setCost")); final List<PassengerVehicle> passengers = new ArrayList<PassengerVehicle>(); addPasenger.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final PassengerVehicle passengerVehicle = new PassengerVehicle(); LinearLayout passenger = (LinearLayout) inflater.inflate(R.layout.passenger, null); linearLayout.addView(passenger); EditText nameEdit = (EditText) passenger.findViewById(R.id.name_edit); nameEdit.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setName")); final EditText dateOfBirth = (EditText) passenger.findViewById(R.id.dob_one); dateOfBirth.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setDate_of_birth")); EditText physicalAddressEdit = (EditText) passenger.findViewById(R.id.physical_address_one); physicalAddressEdit .setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setPhysical_address")); EditText addressBoxEdit = (EditText) passenger.findViewById(R.id.address_box_one); addressBoxEdit.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setAddress")); EditText nationalIDEdit = (EditText) passenger.findViewById(R.id.national_id_one); nationalIDEdit.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setNational_id")); EditText phoneNoEdit = (EditText) passenger.findViewById(R.id.phone_no_one); phoneNoEdit.setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setPhone_no")); EditText alcoholPercentageEdit = (EditText) passenger.findViewById(R.id.alcohol_percentage); alcoholPercentageEdit .setOnFocusChangeListener(new CustomeTimeWatcher(passengerVehicle, "setAlcohol_percent")); CheckBox seatbeltCheckbox = (CheckBox) passenger.findViewById(R.id.seat_belt_check); seatbeltCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { passengerVehicle.setHelmet(isChecked); } }); Button date_picker = (Button) passenger.findViewById(R.id.date_picker); date_picker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DatePickerDialog newDatePickerDialogueFragment; newDatePickerDialogueFragment = new DatePickerDialog(); newDatePickerDialogueFragment.show(AccidentReportFormActivity.fragmentManager, "DatePickerDialogue"); newDatePickerDialogueFragment .setOnDateSetListener(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePickerDialog dialog, int year, int monthOfYear, int dayOfMonth) { dateOfBirth.setText(dayOfMonth + " / " + (monthOfYear + 1) + " / " + year); } }); } }); final RadioButton male = (RadioButton) passenger.findViewById(R.id.male); male.setTypeface(MainOffence.Roboto_Regular); final RadioButton female = (RadioButton) passenger.findViewById(R.id.female); female.setTypeface(MainOffence.Roboto_Regular); passengerVehicle.setGender("Male"); male.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) passengerVehicle.setGender("Male"); } }); female.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) passengerVehicle.setGender("Female"); } }); passengers.add(linearLayout.getChildCount() - 1, passengerVehicle); } }); accident[position] = accidentVehicle; passanger.add(position, passengers); ((ViewPager) container).addView(itemView); return itemView; }
From source file:com.is.rest.cache.CacheAwareCallback.java
@Override public void onSuccess(final int statusCode, final Header[] headers, final String rawResponse, final Result response) { Logger.d("onSuccess: status" + statusCode + " rawResponse: " + rawResponse); ExecutionUtils.execute(new AsyncTask<Void, Void, Result>() { @Override//from w w w .java2s . c o m protected Result doInBackground(Void... voids) { if (response != null && shouldCache()) { try { getCacheManager().put(getCacheInfo().getKey(), response, getCacheInfo()); } catch (IOException e) { Logger.e("cache error", e); } } return response; } @Override protected void onPostExecute(Result result) { Response<Result> httpResponse = new Response<Result>(statusCode, headers, rawResponse, result, null, getCacheInfo()); if (proceedWithResponse()) { timesProcessed++; onResponse(httpResponse); } } }); }
From source file:com.amazon.alexa.avs.companion.LoginWithAmazonActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRequestContext = RequestContext.create(this); mRequestContext.registerListener(new AuthorizeListenerImpl()); setContentView(R.layout.lwa_activity); mAddressTextView = (EditText) findViewById(R.id.addressTextView); mConnectButton = (Button) findViewById(R.id.connectButton); mConnectProgress = (ProgressBar) findViewById(R.id.connectProgressBar); mLoginButton = (ImageButton) findViewById(R.id.loginButton); mLoginProgress = (ProgressBar) findViewById(R.id.loginProgressBar); mLoginMessage = (TextView) findViewById(R.id.loginMessage); connectCleanState();/* w w w. j av a 2 s .com*/ try { mProvisioningClient = new ProvisioningClient(this); } catch (Exception e) { connectErrorState(); showAlertDialog(e); Log.e(TAG, "Unable to use Provisioning Client. CA Certificate is incorrect or does not exist.", e); } String savedDeviceAddress = getPreferences(Context.MODE_PRIVATE) .getString(getString(R.string.saved_device_address), null); if (savedDeviceAddress != null) { mAddressTextView.setText(savedDeviceAddress); } mConnectButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { final String address = mAddressTextView.getText().toString(); mProvisioningClient.setEndpoint(address); new AsyncTask<Void, Void, DeviceProvisioningInfo>() { private Exception errorInBackground; @Override protected void onPreExecute() { super.onPreExecute(); connectInProgressState(); } @Override protected DeviceProvisioningInfo doInBackground(Void... voids) { try { long startTime = System.currentTimeMillis(); DeviceProvisioningInfo response = mProvisioningClient.getDeviceProvisioningInfo(); long duration = System.currentTimeMillis() - startTime; if (duration < MIN_CONNECT_PROGRESS_TIME_MS) { try { Thread.sleep(MIN_CONNECT_PROGRESS_TIME_MS - duration); } catch (InterruptedException e) { e.printStackTrace(); } } return response; } catch (Exception e) { errorInBackground = e; } return null; } @Override protected void onPostExecute(DeviceProvisioningInfo deviceProvisioningInfo) { super.onPostExecute(deviceProvisioningInfo); if (deviceProvisioningInfo != null) { mDeviceProvisioningInfo = deviceProvisioningInfo; SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit(); editor.putString(getString(R.string.saved_device_address), address); editor.commit(); connectSuccessState(); } else { connectCleanState(); showAlertDialog(errorInBackground); } } }.execute(); } }); mLoginButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { loginInProgressState(); final JSONObject scopeData = new JSONObject(); final JSONObject productInstanceAttributes = new JSONObject(); final String codeChallenge = mDeviceProvisioningInfo.getCodeChallenge(); final String codeChallengeMethod = mDeviceProvisioningInfo.getCodeChallengeMethod(); try { productInstanceAttributes.put(DEVICE_SERIAL_NUMBER, mDeviceProvisioningInfo.getDsn()); scopeData.put(PRODUCT_INSTANCE_ATTRIBUTES, productInstanceAttributes); scopeData.put(PRODUCT_ID, mDeviceProvisioningInfo.getProductId()); AuthorizationManager.authorize(new AuthorizeRequest.Builder(mRequestContext) .addScope(ScopeFactory.scopeNamed(ALEXA_ALL_SCOPE, scopeData)) .forGrantType(AuthorizeRequest.GrantType.AUTHORIZATION_CODE) .withProofKeyParameters(codeChallenge, codeChallengeMethod).build()); } catch (JSONException e) { e.printStackTrace(); } } }); }
From source file:com.ymt.demo1.plates.knowledge.KnowledgeItemListViewFragment.java
protected void initView(View view) { /*/* w ww . j ava 2 s . co m*/ *listView */ listView = (PullToRefreshListView) view.findViewById(R.id.pull_to_refresh_list_view); theListView = listView.getRefreshableView(); switch (mKnowledgeType) { case KNOWLEDGE_BZGF: case KNOWLEDGE_KYWX: case KNOWLEDGE_SJK: //?? adapter = new KnowledgeItemAdapter(getActivity()); listView.setAdapter(adapter); adapter.setKnowledgeItemList(knowledgeItemList); new AsyncTask<Void, Void, List<KnowledgeItem>>() { @Override protected List<KnowledgeItem> doInBackground(Void... params) { return DataSupport.where("type = ?", String.valueOf(mKnowledgeType)).find(KnowledgeItem.class); } @Override protected void onPostExecute(List<KnowledgeItem> itemList) { super.onPostExecute(itemList); knowledgeItemList.addAll(itemList); adapter.notifyDataSetChanged(); } }.execute(); break; default: break; } /* *?? */ theListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, long id) { /* *??? */ String[] actionList = new String[] { "", "?" }; PopActionUtil popActionUtil = PopActionUtil.getInstance(getActivity()); actionListener = new PopActionListener() { @Override public void onAction(String action) { switch (action) { case "": Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT).show(); break; case "?": Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT).show(); break; default: break; } } @Override public void onDismiss() { } }; popActionUtil.setActionListener(actionListener); popActionUtil.setActions(actionList); final PopupWindow itemPopMenu = popActionUtil.getSimpleTxtPopActionMenu(); itemPopMenu.showAsDropDown(view, view.getWidth() - 20, -view.getHeight()); itemPopMenu.update(); return true; } }); /* listView ? */ theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Intent intent = new Intent(getActivity(), KnowledgeItemDetailActivity.class); switch (mKnowledgeType) { case KNOWLEDGE_BZGF: case KNOWLEDGE_KYWX: case KNOWLEDGE_SJK: intent.putExtra("knowId", ((KnowledgeItem) parent.getAdapter().getItem(position)).getKnowId()); break; default: break; } startActivity(intent); } }); listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { startIndex = 1; switch (mKnowledgeType) { case KNOWLEDGE_BZGF: case KNOWLEDGE_KYWX: case KNOWLEDGE_SJK: if (AppContext.internetAvialable()) { DataSupport.deleteAll(KnowledgeItem.class, "type = ?", String.valueOf(mKnowledgeType)); knowledgeItemList.clear(); adapter.setKnowledgeItemList(knowledgeItemList); mQueue.add(getListData(pageSize, startIndex, "")); } else { listView.onRefreshComplete(); } break; default: break; } } @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) { startIndex++; switch (mKnowledgeType) { case KNOWLEDGE_BZGF: case KNOWLEDGE_KYWX: case KNOWLEDGE_SJK: if (AppContext.internetAvialable()) { mQueue.add(getListData(pageSize, startIndex, "")); } break; default: break; } } }); }
From source file:org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushRegistrar.java
@Override public void register(final Context context, final Callback<Void> callback) { new AsyncTask<Void, Void, Exception>() { @Override//from w w w . j a v a2 s.co m protected Exception doInBackground(Void... params) { try { if (gcm == null) { gcm = gcmProvider.get(context); } String regid = getRegistrationId(context); if (regid.length() == 0) { regid = gcm.register(senderIds.toArray(new String[] {})); AeroGearGCMPushRegistrar.this.setRegistrationId(context, regid); } deviceToken = regid; HttpProvider httpProvider = httpProviderProvider.get(deviceRegistryURL, TIMEOUT); setPasswordAuthentication(variantId, secret, httpProvider); try { JsonObject postData = new JsonObject(); postData.addProperty("deviceType", deviceType); postData.addProperty("deviceToken", deviceToken); postData.addProperty("alias", alias); postData.addProperty("operatingSystem", operatingSystem); postData.addProperty("osVersion", osVersion); if (categories != null && !categories.isEmpty()) { JsonArray jsonCategories = new JsonArray(); for (String category : categories) { jsonCategories.add(new JsonPrimitive(category)); } postData.add("categories", jsonCategories); } httpProvider.post(postData.toString()); return null; } catch (HttpException ex) { return ex; } } catch (Exception ex) { return ex; } } @SuppressWarnings("unchecked") @Override protected void onPostExecute(Exception result) { if (result == null) { callback.onSuccess(null); } else { if (result instanceof HttpException) { HttpException httpException = (HttpException) result; switch (httpException.getStatusCode()) { case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_TEMPORARY_REDIRECT: Log.w(TAG, httpException.getMessage()); try { URL redirectURL = new URL(httpException.getHeaders().get("Location")); AeroGearGCMPushRegistrar.this.deviceRegistryURL = redirectURL; register(context, callback); } catch (MalformedURLException e) { callback.onFailure(e); } break; default: callback.onFailure(result); } } else { callback.onFailure(result); } } } }.execute((Void) null); }
From source file:com.deployd.Deployd.java
public static void login(String username, String password, final LoginEventHandler loggedIn) { AsyncTask<JSONObject, JSONObject, JSONObject> query = new AsyncTask<JSONObject, JSONObject, JSONObject>() { @Override/*from w w w. j a v a 2s. c o m*/ protected JSONObject doInBackground(JSONObject... arg0) { // TODO Auto-generated method stub try { JSONObject result = Deployd.post(arg0[0], "/users/login"); return result; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(JSONObject result) { // TODO Auto-generated method stub super.onPostExecute(result); if (result == null) { loggedIn.failed(); } DeploydObject jres = new DeploydObject(result); loggedIn.loggedIn(jres); } }; try { JSONObject pass = new JSONObject(); pass.put("username", username); pass.put("password", password); query.execute(pass); } catch (Exception e) { } }