List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:export.UploadManager.java
private void testUserPass(final Uploader l, final JSONObject authConfig, final boolean showPassword) { mSpinner.setTitle("Testing login " + l.getName()); new AsyncTask<Uploader, String, Uploader.Status>() { ContentValues config = new ContentValues(); @Override// w ww . ja v a 2 s. co m protected Uploader.Status doInBackground(Uploader... params) { config.put(Constants.DB.ACCOUNT.AUTH_CONFIG, authConfig.toString()); config.put("_id", l.getId()); l.init(config); try { return params[0].connect(); } catch (Exception ex) { ex.printStackTrace(); return Uploader.Status.ERROR; } } @Override protected void onPostExecute(Uploader.Status result) { handleAuthComplete(l, result); } }.execute(l); }
From source file:eu.faircode.netguard.AdapterRule.java
@Override public void onBindViewHolder(final ViewHolder holder, final int position) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // Get rule/* www .j a v a 2 s. c o m*/ final Rule rule = listFiltered.get(position); // Handle expanding/collapsing holder.llApplication.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rule.expanded = !rule.expanded; notifyItemChanged(position); } }); // Show if non default rules holder.itemView.setBackgroundColor(rule.changed ? colorChanged : Color.TRANSPARENT); // Show expand/collapse indicator holder.ivExpander.setImageLevel(rule.expanded ? 1 : 0); // Show application icon if (rule.info.applicationInfo == null || rule.info.applicationInfo.icon == 0) Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(holder.ivIcon); else { Uri uri = Uri .parse("android.resource://" + rule.info.packageName + "/" + rule.info.applicationInfo.icon); Picasso.with(context).load(uri).resize(iconSize, iconSize).into(holder.ivIcon); } // Show application label holder.tvName.setText(rule.name); // Show application state int color = rule.system ? colorOff : colorText; if (!rule.internet || !rule.enabled) color = Color.argb(128, Color.red(color), Color.green(color), Color.blue(color)); holder.tvName.setTextColor(color); // Show rule count new AsyncTask<Object, Object, Long>() { @Override protected void onPreExecute() { holder.tvHosts.setVisibility(View.GONE); } @Override protected Long doInBackground(Object... objects) { return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid); } @Override protected void onPostExecute(Long rules) { if (rules > 0) { holder.tvHosts.setVisibility(View.VISIBLE); holder.tvHosts.setText(Long.toString(rules)); } } }.execute(); // Wi-Fi settings holder.cbWifi.setEnabled(rule.apply); holder.cbWifi.setAlpha(wifiActive ? 1 : 0.5f); holder.cbWifi.setOnCheckedChangeListener(null); holder.cbWifi.setChecked(rule.wifi_blocked); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbWifi)); DrawableCompat.setTint(wrap, rule.apply ? (rule.wifi_blocked ? colorOff : colorOn) : colorGrayed); } holder.cbWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.wifi_blocked = isChecked; updateRule(rule, true, listAll); } }); holder.ivScreenWifi.setEnabled(rule.apply); holder.ivScreenWifi.setAlpha(wifiActive ? 1 : 0.5f); holder.ivScreenWifi.setVisibility(rule.screen_wifi && rule.wifi_blocked ? View.VISIBLE : View.INVISIBLE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(holder.ivScreenWifi.getDrawable()); DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed); } // Mobile settings holder.cbOther.setEnabled(rule.apply); holder.cbOther.setAlpha(otherActive ? 1 : 0.5f); holder.cbOther.setOnCheckedChangeListener(null); holder.cbOther.setChecked(rule.other_blocked); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbOther)); DrawableCompat.setTint(wrap, rule.apply ? (rule.other_blocked ? colorOff : colorOn) : colorGrayed); } holder.cbOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.other_blocked = isChecked; updateRule(rule, true, listAll); } }); holder.ivScreenOther.setEnabled(rule.apply); holder.ivScreenOther.setAlpha(otherActive ? 1 : 0.5f); holder.ivScreenOther.setVisibility(rule.screen_other && rule.other_blocked ? View.VISIBLE : View.INVISIBLE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(holder.ivScreenOther.getDrawable()); DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed); } holder.tvRoaming.setTextColor(rule.apply ? colorOff : colorGrayed); holder.tvRoaming.setAlpha(otherActive ? 1 : 0.5f); holder.tvRoaming.setVisibility( rule.roaming && (!rule.other_blocked || rule.screen_other) ? View.VISIBLE : View.INVISIBLE); // Expanded configuration section holder.llConfiguration.setVisibility(rule.expanded ? View.VISIBLE : View.GONE); // Show application details holder.tvUid .setText(rule.info.applicationInfo == null ? "?" : Integer.toString(rule.info.applicationInfo.uid)); holder.tvPackage.setText(rule.info.packageName); holder.tvVersion.setText(rule.info.versionName + '/' + rule.info.versionCode); holder.tvDescription.setVisibility(rule.description == null ? View.GONE : View.VISIBLE); holder.tvDescription.setText(rule.description); // Show application state holder.tvInternet.setVisibility(rule.internet ? View.GONE : View.VISIBLE); holder.tvDisabled.setVisibility(rule.enabled ? View.GONE : View.VISIBLE); // Show traffic statistics holder.tvStatistics.setText(context.getString(R.string.msg_mbday, rule.upspeed, rule.downspeed)); // Apply holder.cbApply.setEnabled(rule.pkg); holder.cbApply.setOnCheckedChangeListener(null); holder.cbApply.setChecked(rule.apply); holder.cbApply.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.apply = isChecked; updateRule(rule, true, listAll); } }); // Show related holder.btnRelated.setVisibility(rule.relateduids ? View.VISIBLE : View.GONE); holder.btnRelated.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent main = new Intent(context, ActivityMain.class); main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(rule.info.applicationInfo.uid)); context.startActivity(main); } }); // Fetch settings holder.ibFetch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AsyncTask<Object, Object, Object>() { @Override protected void onPreExecute() { holder.ibFetch.setEnabled(false); } @Override protected Object doInBackground(Object... args) { HttpsURLConnection urlConnection = null; try { JSONObject json = new JSONObject(); json.put("type", "fetch"); json.put("country", Locale.getDefault().getCountry()); json.put("netguard", Util.getSelfVersionCode(context)); json.put("fingerprint", Util.getFingerprint(context)); JSONObject pkg = new JSONObject(); pkg.put("name", rule.info.packageName); pkg.put("version_code", rule.info.versionCode); pkg.put("version_name", rule.info.versionName); JSONArray pkgs = new JSONArray(); pkgs.put(pkg); json.put("package", pkgs); urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection(); urlConnection.setConnectTimeout(cTimeOutMs); urlConnection.setReadTimeout(cTimeOutMs); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Content-type", "application/json"); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); Log.i(TAG, "Request=" + json.toString()); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(json.toString().getBytes()); // UTF-8 out.flush(); int code = urlConnection.getResponseCode(); if (code != HttpsURLConnection.HTTP_OK) throw new IOException("HTTP " + code); InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream()); String response = Util.readString(isr).toString(); Log.i(TAG, "Response=" + response); JSONObject jfetched = new JSONObject(response); JSONArray jpkgs = jfetched.getJSONArray("package"); for (int i = 0; i < jpkgs.length(); i++) { JSONObject jpkg = jpkgs.getJSONObject(i); String name = jpkg.getString("name"); int wifi = jpkg.getInt("wifi"); int wifi_screen = jpkg.getInt("wifi_screen"); int other = jpkg.getInt("other"); int other_screen = jpkg.getInt("other_screen"); int roaming = jpkg.getInt("roaming"); int devices = jpkg.getInt("devices"); double conf_wifi; boolean block_wifi; if (rule.wifi_default) { conf_wifi = confidence(devices - wifi, devices); block_wifi = !(devices - wifi > wifi && conf_wifi > cConfidence); } else { conf_wifi = confidence(wifi, devices); block_wifi = (wifi > devices - wifi && conf_wifi > cConfidence); } boolean allow_wifi_screen = rule.screen_wifi_default; if (block_wifi) allow_wifi_screen = (wifi_screen > wifi / 2); double conf_other; boolean block_other; if (rule.other_default) { conf_other = confidence(devices - other, devices); block_other = !(devices - other > other && conf_other > cConfidence); } else { conf_other = confidence(other, devices); block_other = (other > devices - other && conf_other > cConfidence); } boolean allow_other_screen = rule.screen_other_default; if (block_other) allow_other_screen = (other_screen > other / 2); boolean block_roaming = rule.roaming_default; if (!block_other || allow_other_screen) block_roaming = (roaming > (devices - other) / 2); Log.i(TAG, "pkg=" + name + " wifi=" + wifi + "/" + wifi_screen + "=" + block_wifi + "/" + allow_wifi_screen + " " + Math.round(100 * conf_wifi) + "%" + " other=" + other + "/" + other_screen + "/" + roaming + "=" + block_other + "/" + allow_other_screen + "/" + block_roaming + " " + Math.round(100 * conf_other) + "%" + " devices=" + devices); rule.wifi_blocked = block_wifi; rule.screen_wifi = allow_wifi_screen; rule.other_blocked = block_other; rule.screen_other = allow_other_screen; rule.roaming = block_roaming; } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); return ex; } finally { if (urlConnection != null) urlConnection.disconnect(); } return null; } @Override protected void onPostExecute(Object result) { holder.ibFetch.setEnabled(true); updateRule(rule, true, listAll); } }.execute(rule); } }); // Launch application settings final Intent settings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); settings.setData(Uri.parse("package:" + rule.info.packageName)); holder.ibSettings.setVisibility( settings.resolveActivity(context.getPackageManager()) == null ? View.GONE : View.VISIBLE); holder.ibSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(settings); } }); // Launch application holder.ibLaunch.setVisibility(rule.intent == null ? View.GONE : View.VISIBLE); holder.ibLaunch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(rule.intent); } }); // Show Wi-Fi screen on condition holder.cbScreenWifi.setEnabled(rule.wifi_blocked && rule.apply); holder.cbScreenWifi.setOnCheckedChangeListener(null); holder.cbScreenWifi.setChecked(rule.screen_wifi); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(holder.ivWifiLegend.getDrawable()); DrawableCompat.setTint(wrap, colorOn); } holder.cbScreenWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { rule.screen_wifi = isChecked; updateRule(rule, true, listAll); } }); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable()); DrawableCompat.setTint(wrap, colorOn); } // Show mobile screen on condition holder.cbScreenOther.setEnabled(rule.other_blocked && rule.apply); holder.cbScreenOther.setOnCheckedChangeListener(null); holder.cbScreenOther.setChecked(rule.screen_other); holder.cbScreenOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { rule.screen_other = isChecked; updateRule(rule, true, listAll); } }); // Show roaming condition holder.cbRoaming.setEnabled((!rule.other_blocked || rule.screen_other) && rule.apply); holder.cbRoaming.setOnCheckedChangeListener(null); holder.cbRoaming.setChecked(rule.roaming); holder.cbRoaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @TargetApi(Build.VERSION_CODES.M) public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { rule.roaming = isChecked; updateRule(rule, true, listAll); // Request permissions if (isChecked && !Util.hasPhoneStatePermission(context)) context.requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE }, ActivityMain.REQUEST_ROAMING); } }); // Reset rule holder.btnClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Util.areYouSure(view.getContext(), R.string.msg_clear_rules, new Util.DoubtListener() { @Override public void onSure() { holder.cbApply.setChecked(true); holder.cbWifi.setChecked(rule.wifi_default); holder.cbOther.setChecked(rule.other_default); holder.cbScreenWifi.setChecked(rule.screen_wifi_default); holder.cbScreenOther.setChecked(rule.screen_other_default); holder.cbRoaming.setChecked(rule.roaming_default); } }); } }); // Show logging is disabled boolean log_app = prefs.getBoolean("log_app", false); holder.tvNoLog.setVisibility(log_app ? View.GONE : View.VISIBLE); holder.tvNoLog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(new Intent(context, ActivitySettings.class)); } }); // Show filtering is disabled boolean filter = prefs.getBoolean("filter", false); holder.tvNoFilter.setVisibility(filter ? View.GONE : View.VISIBLE); holder.tvNoFilter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(new Intent(context, ActivitySettings.class)); } }); // Show access rules if (rule.expanded) { // Access the database when expanded only final AdapterAccess badapter = new AdapterAccess(context, DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid)); holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int bposition, long bid) { PackageManager pm = context.getPackageManager(); Cursor cursor = (Cursor) badapter.getItem(bposition); final long id = cursor.getLong(cursor.getColumnIndex("ID")); final int version = cursor.getInt(cursor.getColumnIndex("version")); final int protocol = cursor.getInt(cursor.getColumnIndex("protocol")); final String daddr = cursor.getString(cursor.getColumnIndex("daddr")); final int dport = cursor.getInt(cursor.getColumnIndex("dport")); long time = cursor.getLong(cursor.getColumnIndex("time")); int block = cursor.getInt(cursor.getColumnIndex("block")); PopupMenu popup = new PopupMenu(context, context.findViewById(R.id.vwPopupAnchor)); popup.inflate(R.menu.access); popup.getMenu().findItem(R.id.menu_host).setTitle(Util.getProtocolName(protocol, version, false) + " " + daddr + (dport > 0 ? "/" + dport : "")); // Whois final Intent lookupIP = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.tcpiputils.com/whois-lookup/" + daddr)); if (pm.resolveActivity(lookupIP, 0) == null) popup.getMenu().removeItem(R.id.menu_whois); else popup.getMenu().findItem(R.id.menu_whois) .setTitle(context.getString(R.string.title_log_whois, daddr)); // Lookup port final Intent lookupPort = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.speedguide.net/port.php?port=" + dport)); if (dport <= 0 || pm.resolveActivity(lookupPort, 0) == null) popup.getMenu().removeItem(R.id.menu_port); else popup.getMenu().findItem(R.id.menu_port) .setTitle(context.getString(R.string.title_log_port, dport)); popup.getMenu().findItem(R.id.menu_time) .setTitle(SimpleDateFormat.getDateTimeInstance().format(time)); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_whois: context.startActivity(lookupIP); return true; case R.id.menu_port: context.startActivity(lookupPort); return true; case R.id.menu_allow: if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) { DatabaseHelper.getInstance(context).setAccess(id, 0); ServiceSinkhole.reload("allow host", context); if (rule.submit) ServiceJob.submit(rule, version, protocol, daddr, dport, 0, context); } else context.startActivity(new Intent(context, ActivityPro.class)); return true; case R.id.menu_block: if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) { DatabaseHelper.getInstance(context).setAccess(id, 1); ServiceSinkhole.reload("block host", context); if (rule.submit) ServiceJob.submit(rule, version, protocol, daddr, dport, 1, context); } else context.startActivity(new Intent(context, ActivityPro.class)); return true; case R.id.menu_reset: DatabaseHelper.getInstance(context).setAccess(id, -1); ServiceSinkhole.reload("reset host", context); if (rule.submit) ServiceJob.submit(rule, version, protocol, daddr, dport, -1, context); return true; } return false; } }); if (block == 0) popup.getMenu().removeItem(R.id.menu_allow); else if (block == 1) popup.getMenu().removeItem(R.id.menu_block); popup.show(); } }); holder.lvAccess.setAdapter(badapter); } else { holder.lvAccess.setAdapter(null); holder.lvAccess.setOnItemClickListener(null); } // Clear access log holder.btnClearAccess.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() { @Override public void onSure() { DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid, true); if (rv != null) rv.scrollToPosition(position); } }); } }); // Notify on access holder.cbNotify.setEnabled(prefs.getBoolean("notify_access", false) && rule.apply); holder.cbNotify.setOnCheckedChangeListener(null); holder.cbNotify.setChecked(rule.notify); holder.cbNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.notify = isChecked; updateRule(rule, true, listAll); } }); // Usage data sharing holder.cbSubmit .setVisibility(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? View.VISIBLE : View.GONE); holder.cbSubmit.setOnCheckedChangeListener(null); holder.cbSubmit.setChecked(rule.submit); holder.cbSubmit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { rule.submit = isChecked; updateRule(rule, true, listAll); } }); }
From source file:info.guardianproject.gpg.KeyListFragment.java
private void keyserverOperation(final int operation, final ActionMode mode) { new AsyncTask<Void, Void, Void>() { final Context context = getActivity().getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER, "ipv4.pool.sks-keyservers.net"); final long[] selected = mListView.getCheckedItemIds(); final Intent intent = new Intent(context, ImportFileActivity.class); @Override//from w w w . j a v a 2 s . c o m protected Void doInBackground(Void... params) { HkpKeyServer keyserver = new HkpKeyServer(host); if (operation == DELETE_KEYS) { String args = "--batch --yes --delete-keys"; for (int i = 0; i < selected.length; i++) { args += " " + Long.toHexString(selected[i]); } GnuPG.gpg2(args); } else if (operation == KEYSERVER_SEND) { String args = "--keyserver " + host + " --send-keys "; for (int i = 0; i < selected.length; i++) { args += " " + Long.toHexString(selected[i]); } // TODO this should use the Java keyserver stuff GnuPG.gpg2(args); } else if (operation == KEYSERVER_RECEIVE) { String keys = ""; for (int i = 0; i < selected.length; i++) { try { keys += keyserver.get(selected[i]); keys += "\n\n"; } catch (QueryException e) { e.printStackTrace(); } } // An Intent can carry very much data, so write it // to a cached file try { File privateFile = File.createTempFile("keyserver", ".pkr", mCurrentActivity.getCacheDir()); FileUtils.writeStringToFile(privateFile, keys); intent.setType(getString(R.string.pgp_keys)); intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(privateFile)); } catch (IOException e) { e.printStackTrace(); // try sending the key data inline in the Intent intent.setType("text/plain"); intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, keys); } } return null; } @Override protected void onPostExecute(Void v) { GpgApplication.triggerContactsSync(); mCurrentActivity.setSupportProgressBarIndeterminateVisibility(false); mode.finish(); // Action picked, so close the CAB if (operation == KEYSERVER_RECEIVE) startActivity(intent); } }.execute(); }
From source file:org.anhonesteffort.flock.SubscriptionGoogleFragment.java
private void handleLoadSkuList(final String productType) { if (asyncTask != null) return;/* w w w . j ava 2 s . c o m*/ asyncTask = new AsyncTask<Void, Void, Bundle>() { @Override protected void onPreExecute() { Log.d(TAG, "handleLoadSkuList"); subscriptionActivity.setProgressBarIndeterminateVisibility(true); subscriptionActivity.setProgressBarVisibility(true); } private ArrayList<String> getSkuDetails(ArrayList<String> skuList, Bundle result) throws RemoteException { Bundle skuBundle = new Bundle(); skuBundle.putStringArrayList("ITEM_ID_LIST", skuList); Bundle skuDetails = subscriptionActivity.billingService.getSkuDetails(3, SubscriptionGoogleFragment.class.getPackage().getName(), productType, skuBundle); if (skuDetails.getInt("RESPONSE_CODE") == 0) return skuDetails.getStringArrayList("DETAILS_LIST"); else { Log.e(TAG, "sku details response code is != 0"); result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR); return new ArrayList<String>(0); } } @Override protected Bundle doInBackground(Void... params) { Bundle result = new Bundle(); if (subscriptionActivity.billingService == null) { Log.e(TAG, "billing service is null"); result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR); return result; } ArrayList<String> skuQueryList = new ArrayList<String>(2); skuQueryList.add(SKU_YEARLY_SUBSCRIPTION); try { List<String> skuDetails = getSkuDetails(skuQueryList, result); ArrayList<String> skuList = new ArrayList<String>(); if (result.getInt(ErrorToaster.KEY_STATUS_CODE, -1) != -1) return result; for (String thisResponse : skuDetails) { JSONObject productObject = new JSONObject(thisResponse); skuList.add(productObject.getString("productId")); } result.putStringArrayList("SKU_LIST", skuList); result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS); } catch (JSONException e) { Log.e(TAG, "error parsing sku details", e); result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR); } catch (RemoteException e) { Log.e(TAG, "error parsing sku details", e); result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR); } return result; } @Override protected void onPostExecute(Bundle result) { asyncTask = null; subscriptionActivity.setProgressBarIndeterminateVisibility(false); subscriptionActivity.setProgressBarVisibility(false); if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS) handleSkuListLoaded(result.getStringArrayList("SKU_LIST")); else ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result); } }.execute(); }
From source file:com.mozilla.simplepush.simplepushdemoapp.MainActivity.java
/** Send the notification to SimplePush * * This is normally what the App Server would do. We're handling it ourselves because * this app is self-contained.// ww w. j av a 2s . c o m * * @param data the notification string. */ private void SendNotification(final String data) { if (PushEndpoint.length() == 0) { return; } // Run as a background task, passing the data string and getting a success bool. new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... params) { HttpPut req = new HttpPut(PushEndpoint); // HttpParams is NOT what you use here. // NameValuePairs is just a simple hash. List<NameValuePair> rparams = new ArrayList<>(2); rparams.add(new BasicNameValuePair("version", String.valueOf(System.currentTimeMillis()))); // While we're just using a simple string here, there's no reason you couldn't // have this be up to 4K of JSON. Just make sure that the GcmIntentService handler // knows what to do with it. rparams.add(new BasicNameValuePair("data", data)); Log.i(TAG, "Sending data: " + data); try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(rparams); Log.i(TAG, "params:" + rparams.toString() + " entity: " + entity.toString()); entity.setContentType("application/x-www-form-urlencoded"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "text/plain;charset=UTF-8")); req.setEntity(entity); req.addHeader("Authorization", genSignature(entity)); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse resp = client.execute(req); int code = resp.getStatusLine().getStatusCode(); if (code >= 200 && code < 300) { return true; } } catch (ClientProtocolException x) { Log.e(TAG, "Could not send Notification " + x); } catch (IOException x) { Log.e(TAG, "Could not send Notification (io) " + x); } catch (Exception e) { Log.e(TAG, "flaming crapsticks", e); } return false; } /** Report back on what just happened. * * @param success Status of post execution */ @Override protected void onPostExecute(Boolean success) { String msg = "was"; if (!success) { msg = "was not"; } mDisplay.setText("Message " + msg + " sent"); } }.execute(data, null, null); }
From source file:com.odoo.addons.sale.models.SaleOrder.java
public void newCopyQuotation(final ODataRow quotation, final OnOperationSuccessListener listener) { new AsyncTask<Void, Void, Void>() { private ProgressDialog dialog; @Override// ww w . ja v a 2s. c om protected void onPreExecute() { super.onPreExecute(); dialog = new ProgressDialog(mContext); dialog.setTitle(R.string.title_please_wait); dialog.setMessage(OResource.string(mContext, R.string.title_working)); dialog.setCancelable(false); dialog.show(); } @Override protected Void doInBackground(Void... params) { try { OArguments args = new OArguments(); args.add(new JSONArray().put(quotation.getInt("id"))); args.add(new JSONObject()); getServerDataHelper().callMethod("copy_quotation", args); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); dialog.dismiss(); if (listener != null) { listener.OnSuccess(); } } @Override protected void onCancelled() { super.onCancelled(); dialog.dismiss(); if (listener != null) { listener.OnCancelled(); } } }.execute(); }
From source file:com.piusvelte.sonet.core.SonetService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if (ACTION_REFRESH.equals(action)) { if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1); else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 1); else if (intent.getData() != null) putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1); else//from w ww. j a v a 2 s. c om putValidatedUpdates(null, 0); } else if (LauncherIntent.Action.ACTION_READY.equals(action)) { if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION) && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // check if the scrollable needs to be built Cursor widget = this.getContentResolver().query(Widgets.getContentUri(SonetService.this), new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }, null); if (widget.moveToFirst()) { if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } else putValidatedUpdates(new int[] { appWidgetId }, 1); } else { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } widget.close(); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { // requery putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 0); } } else if (SMS_RECEIVED.equals(action)) { // parse the sms, and notify any widgets which have sms enabled Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() { @Override protected int[] doInBackground(SmsMessage... msg) { // check if SMS is enabled anywhere Cursor widgets = getContentResolver().query( Widget_accounts_view.getContentUri(SonetService.this), new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET, Widget_accounts_view.ACCOUNT }, Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); int[] appWidgetIds = new int[widgets.getCount()]; if (widgets.moveToFirst()) { // insert this message to the statuses db and requery scrollable/rebuild widget // check if this is a contact String phone = msg[0].getOriginatingAddress(); String friend = phone; byte[] profile = null; Uri content_uri = null; // unknown numbers crash here in the emulator Cursor phones = getContentResolver().query( Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); if (phones.moveToFirst()) content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, phones.getLong(0)); else { Cursor emails = getContentResolver().query( Uri.withAppendedPath( ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null, null); if (emails.moveToFirst()) content_uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, emails.getLong(0)); emails.close(); } phones.close(); if (content_uri != null) { // load contact Cursor contacts = getContentResolver().query(content_uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (contacts.moveToFirst()) friend = contacts.getString(0); contacts.close(); profile = getBlob(ContactsContract.Contacts .openContactPhotoInputStream(getContentResolver(), content_uri)); } long accountId = widgets.getLong(2); long id; ContentValues values = new ContentValues(); values.put(Entities.ESID, phone); values.put(Entities.FRIEND, friend); values.put(Entities.PROFILE, profile); values.put(Entities.ACCOUNT, accountId); Cursor entity = getContentResolver().query( Entities.getContentUri(SonetService.this), new String[] { Entities._ID }, Entities.ACCOUNT + "=? and " + Entities.ESID + "=?", new String[] { Long.toString(accountId), mSonetCrypto.Encrypt(phone) }, null); if (entity.moveToFirst()) { id = entity.getLong(0); getContentResolver().update(Entities.getContentUri(SonetService.this), values, Entities._ID + "=?", new String[] { Long.toString(id) }); } else id = Long.parseLong(getContentResolver() .insert(Entities.getContentUri(SonetService.this), values) .getLastPathSegment()); entity.close(); values.clear(); Long created = msg[0].getTimestampMillis(); values.put(Statuses.CREATED, created); values.put(Statuses.ENTITY, id); values.put(Statuses.MESSAGE, msg[0].getMessageBody()); values.put(Statuses.SERVICE, SMS); while (!widgets.isAfterLast()) { int widget = widgets.getInt(1); appWidgetIds[widgets.getPosition()] = widget; // get settings boolean time24hr = true; int status_bg_color = Sonet.default_message_bg_color; int profile_bg_color = Sonet.default_message_bg_color; int friend_bg_color = Sonet.default_friend_bg_color; boolean icon = true; int status_count = Sonet.default_statuses_per_account; int notifications = 0; Cursor c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) initAccountSettings(SonetService.this, AppWidgetManager.INVALID_APPWIDGET_ID, Sonet.INVALID_ACCOUNT_ID); if (widget != AppWidgetManager.INVALID_APPWIDGET_ID) initAccountSettings(SonetService.this, widget, Sonet.INVALID_ACCOUNT_ID); } initAccountSettings(SonetService.this, widget, accountId); } if (c.moveToFirst()) { time24hr = c.getInt(0) == 1; status_bg_color = c.getInt(1); icon = c.getInt(2) == 1; status_count = c.getInt(3); if (c.getInt(4) == 1) notifications |= Notification.DEFAULT_SOUND; if (c.getInt(5) == 1) notifications |= Notification.DEFAULT_VIBRATE; if (c.getInt(6) == 1) notifications |= Notification.DEFAULT_LIGHTS; profile_bg_color = c.getInt(7); friend_bg_color = c.getInt(8); } c.close(); values.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(created, time24hr)); // update the bg and icon // create the status_bg values.put(Statuses.STATUS_BG, createBackground(status_bg_color)); // friend_bg values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color)); // profile_bg values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color)); values.put(Statuses.ICON, icon ? getBlob(getResources(), map_icons[SMS]) : null); // insert the message values.put(Statuses.WIDGET, widget); values.put(Statuses.ACCOUNT, accountId); getContentResolver().insert(Statuses.getContentUri(SonetService.this), values); // check the status count, removing old sms Cursor statuses = getContentResolver().query( Statuses.getContentUri(SonetService.this), new String[] { Statuses._ID }, Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, Statuses.CREATED + " desc"); if (statuses.moveToFirst()) { while (!statuses.isAfterLast()) { if (statuses.getPosition() >= status_count) { getContentResolver().delete( Statuses.getContentUri(SonetService.this), Statuses._ID + "=?", new String[] { Long.toString(statuses .getLong(statuses.getColumnIndex(Statuses._ID))) }); } statuses.moveToNext(); } } statuses.close(); if (notifications != 0) publishProgress(Integer.toString(notifications), friend + " sent a message"); widgets.moveToNext(); } } widgets.close(); return appWidgetIds; } @Override protected void onProgressUpdate(String... updates) { int notifications = Integer.parseInt(updates[0]); if (notifications != 0) { Notification notification = new Notification(R.drawable.notification, updates[1], System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1], PendingIntent.getActivity(SonetService.this, 0, (Sonet .getPackageIntent(SonetService.this, SonetNotifications.class)), 0)); notification.defaults |= notifications; ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFY_ID, notification); } } @Override protected void onPostExecute(int[] appWidgetIds) { // remove self from thread list if (!mSMSLoaders.isEmpty()) mSMSLoaders.remove(this); putValidatedUpdates(appWidgetIds, 0); } }; mSMSLoaders.add(smsLoader); smsLoader.execute(msg); } } else if (ACTION_PAGE_DOWN.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_DOWN, 0)); else if (ACTION_PAGE_UP.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_UP, 0)); else { // this might be a widget update from the widget refresh button int appWidgetId; try { appWidgetId = Integer.parseInt(action); putValidatedUpdates(new int[] { appWidgetId }, 1); } catch (NumberFormatException e) { Log.d(TAG, "unknown action:" + action); } } } }
From source file:ca.rmen.android.scrumchatter.main.MainActivity.java
/** * Share a file using an intent chooser. * /*w w w. jav a 2 s . c o m*/ * @param fileExport The object responsible for creating the file to share. */ private void shareFile(final FileExport fileExport) { final ProgressDialog progressDialog = ProgressDialog.show(this, null, getString(R.string.progress_dialog_message), true); AsyncTask<Void, Void, Boolean> asyncTask = new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return fileExport.export(); } @Override protected void onPreExecute() { progressDialog.show(); } @Override protected void onPostExecute(Boolean success) { progressDialog.dismiss(); if (!success) Toast.makeText(MainActivity.this, R.string.export_error, Toast.LENGTH_LONG).show(); } }; asyncTask.execute(); }
From source file:com.shafiq.myfeedle.core.MyfeedleComments.java
@Override public void onClick(View v) { if (v == mSend) { if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0) && (mSid != null) && (mEsid != null)) { mMessage.setEnabled(false);/* w w w . j a va 2 s. c om*/ mSend.setEnabled(false); // post or comment! final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() { @Override protected String doInBackground(Void... arg0) { List<NameValuePair> params; String message; String response = null; HttpPost httpPost; MyfeedleOAuth myfeedleOAuth; String serviceName = Myfeedle.getServiceName(getResources(), mService); publishProgress(serviceName); switch (mService) { case TWITTER: // limit tweets to 140, breaking up the message if necessary myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case FACEBOOK: httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString())); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case MYSPACE: myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret); try { httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid)); httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY, mMessage.getText().toString()))); response = MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8"); httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL, mSid, message, mToken)); response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case LINKEDIN: myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret); try { httpPost = new HttpPost( String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid)); httpPost.setEntity(new StringEntity( String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString()))); httpPost.addHeader(new BasicHeader("Content-Type", "application/xml")); response = MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case IDENTICA: // limit tweets to 140, breaking up the message if necessary myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case GOOGLEPLUS: break; case CHATTER: httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid, Uri.encode(mMessage.getText().toString()))); httpPost.setHeader("Authorization", "OAuth " + mChatterToken); response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost); break; } return ((response == null) && (mService == MYSPACE)) ? null : serviceName + " " + getString(response != null ? R.string.success : R.string.failure); } @Override protected void onProgressUpdate(String... params) { loadingDialog.setMessage(String.format(getString(R.string.sending), params[0])); } @Override protected void onPostExecute(String result) { if (result != null) { (Toast.makeText(MyfeedleComments.this, result, Toast.LENGTH_LONG)).show(); } else if (mService == MYSPACE) { // myspace permissions (Toast.makeText(MyfeedleComments.this, MyfeedleComments.this.getResources() .getStringArray(R.array.service_entries)[MYSPACE] + getString(R.string.failure) + " " + getString(R.string.myspace_permissions_message), Toast.LENGTH_LONG)).show(); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); finish(); } }; 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(); } else { (Toast.makeText(MyfeedleComments.this, "error parsing message body", Toast.LENGTH_LONG)).show(); mMessage.setEnabled(true); mSend.setEnabled(true); } } }
From source file:com.shafiq.myfeedle.core.MyfeedleService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if (ACTION_REFRESH.equals(action)) { if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1); else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 1); else if (intent.getData() != null) putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1); else/*w w w . j a v a 2s. c o m*/ putValidatedUpdates(null, 0); } else if (LauncherIntent.Action.ACTION_READY.equals(action)) { if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION) && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // check if the scrollable needs to be built Cursor widget = this.getContentResolver().query(Widgets.getContentUri(MyfeedleService.this), new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }, null); if (widget.moveToFirst()) { if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } else putValidatedUpdates(new int[] { appWidgetId }, 1); } else { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } widget.close(); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { // requery putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 0); } } else if (SMS_RECEIVED.equals(action)) { // parse the sms, and notify any widgets which have sms enabled Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() { @Override protected int[] doInBackground(SmsMessage... msg) { // check if SMS is enabled anywhere Cursor widgets = getContentResolver().query( Widget_accounts_view.getContentUri(MyfeedleService.this), new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET, Widget_accounts_view.ACCOUNT }, Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); int[] appWidgetIds = new int[widgets.getCount()]; if (widgets.moveToFirst()) { // insert this message to the statuses db and requery scrollable/rebuild widget // check if this is a contact String phone = msg[0].getOriginatingAddress(); String friend = phone; byte[] profile = null; Uri content_uri = null; // unknown numbers crash here in the emulator Cursor phones = getContentResolver().query( Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); if (phones.moveToFirst()) content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, phones.getLong(0)); else { Cursor emails = getContentResolver().query( Uri.withAppendedPath( ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null, null); if (emails.moveToFirst()) content_uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, emails.getLong(0)); emails.close(); } phones.close(); if (content_uri != null) { // load contact Cursor contacts = getContentResolver().query(content_uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (contacts.moveToFirst()) friend = contacts.getString(0); contacts.close(); profile = getBlob(ContactsContract.Contacts .openContactPhotoInputStream(getContentResolver(), content_uri)); } long accountId = widgets.getLong(2); long id; ContentValues values = new ContentValues(); values.put(Entities.ESID, phone); values.put(Entities.FRIEND, friend); values.put(Entities.PROFILE, profile); values.put(Entities.ACCOUNT, accountId); Cursor entity = getContentResolver().query( Entities.getContentUri(MyfeedleService.this), new String[] { Entities._ID }, Entities.ACCOUNT + "=? and " + Entities.ESID + "=?", new String[] { Long.toString(accountId), mMyfeedleCrypto.Encrypt(phone) }, null); if (entity.moveToFirst()) { id = entity.getLong(0); getContentResolver().update(Entities.getContentUri(MyfeedleService.this), values, Entities._ID + "=?", new String[] { Long.toString(id) }); } else id = Long.parseLong(getContentResolver() .insert(Entities.getContentUri(MyfeedleService.this), values) .getLastPathSegment()); entity.close(); values.clear(); Long created = msg[0].getTimestampMillis(); values.put(Statuses.CREATED, created); values.put(Statuses.ENTITY, id); values.put(Statuses.MESSAGE, msg[0].getMessageBody()); values.put(Statuses.SERVICE, SMS); while (!widgets.isAfterLast()) { int widget = widgets.getInt(1); appWidgetIds[widgets.getPosition()] = widget; // get settings boolean time24hr = true; int status_bg_color = Myfeedle.default_message_bg_color; int profile_bg_color = Myfeedle.default_message_bg_color; int friend_bg_color = Myfeedle.default_friend_bg_color; boolean icon = true; int status_count = Myfeedle.default_statuses_per_account; int notifications = 0; Cursor c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(Myfeedle.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Myfeedle.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) initAccountSettings(MyfeedleService.this, AppWidgetManager.INVALID_APPWIDGET_ID, Myfeedle.INVALID_ACCOUNT_ID); if (widget != AppWidgetManager.INVALID_APPWIDGET_ID) initAccountSettings(MyfeedleService.this, widget, Myfeedle.INVALID_ACCOUNT_ID); } initAccountSettings(MyfeedleService.this, widget, accountId); } if (c.moveToFirst()) { time24hr = c.getInt(0) == 1; status_bg_color = c.getInt(1); icon = c.getInt(2) == 1; status_count = c.getInt(3); if (c.getInt(4) == 1) notifications |= Notification.DEFAULT_SOUND; if (c.getInt(5) == 1) notifications |= Notification.DEFAULT_VIBRATE; if (c.getInt(6) == 1) notifications |= Notification.DEFAULT_LIGHTS; profile_bg_color = c.getInt(7); friend_bg_color = c.getInt(8); } c.close(); values.put(Statuses.CREATEDTEXT, Myfeedle.getCreatedText(created, time24hr)); // update the bg and icon // create the status_bg values.put(Statuses.STATUS_BG, createBackground(status_bg_color)); // friend_bg values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color)); // profile_bg values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color)); values.put(Statuses.ICON, icon ? getBlob(getResources(), map_icons[SMS]) : null); // insert the message values.put(Statuses.WIDGET, widget); values.put(Statuses.ACCOUNT, accountId); getContentResolver().insert(Statuses.getContentUri(MyfeedleService.this), values); // check the status count, removing old sms Cursor statuses = getContentResolver().query( Statuses.getContentUri(MyfeedleService.this), new String[] { Statuses._ID }, Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, Statuses.CREATED + " desc"); if (statuses.moveToFirst()) { while (!statuses.isAfterLast()) { if (statuses.getPosition() >= status_count) { getContentResolver().delete( Statuses.getContentUri(MyfeedleService.this), Statuses._ID + "=?", new String[] { Long.toString(statuses .getLong(statuses.getColumnIndex(Statuses._ID))) }); } statuses.moveToNext(); } } statuses.close(); if (notifications != 0) publishProgress(Integer.toString(notifications), friend + " sent a message"); widgets.moveToNext(); } } widgets.close(); return appWidgetIds; } @Override protected void onProgressUpdate(String... updates) { int notifications = Integer.parseInt(updates[0]); if (notifications != 0) { Notification notification = new Notification(R.drawable.notification, updates[1], System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1], PendingIntent.getActivity(MyfeedleService.this, 0, (Myfeedle.getPackageIntent(MyfeedleService.this, MyfeedleNotifications.class)), 0)); notification.defaults |= notifications; ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFY_ID, notification); } } @Override protected void onPostExecute(int[] appWidgetIds) { // remove self from thread list if (!mSMSLoaders.isEmpty()) mSMSLoaders.remove(this); putValidatedUpdates(appWidgetIds, 0); } }; mSMSLoaders.add(smsLoader); smsLoader.execute(msg); } } else if (ACTION_PAGE_DOWN.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_DOWN, 0)); else if (ACTION_PAGE_UP.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_UP, 0)); else { // this might be a widget update from the widget refresh button int appWidgetId; try { appWidgetId = Integer.parseInt(action); putValidatedUpdates(new int[] { appWidgetId }, 1); } catch (NumberFormatException e) { Log.d(TAG, "unknown action:" + action); } } } }