List of usage examples for android.os StrictMode setThreadPolicy
public static void setThreadPolicy(final ThreadPolicy policy)
From source file:com.dwdesign.tweetings.fragment.BaseStatusesListFragment.java
protected void translate(final ParcelableStatus status) { ThreadPolicy tp = ThreadPolicy.LAX; StrictMode.setThreadPolicy(tp); String language = Locale.getDefault().getLanguage(); String url = "http://api.microsofttranslator.com/v2/Http.svc/Translate?contentType=" + URLEncoder.encode("text/plain") + "&appId=" + BING_TRANSLATE_API_KEY + "&from=&to=" + language + "&text="; url = url + URLEncoder.encode(status.text_plain); try {/*from w ww . ja v a 2 s. c o m*/ HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(new HttpGet(url)); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String sResponse; StringBuilder s = new StringBuilder(); while ((sResponse = reader.readLine()) != null) { s = s.append(sResponse); } String finalString = s.toString(); finalString = finalString .replace("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">", ""); finalString = finalString.replace("</string>", ""); AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity()); builder.setTitle(getString(R.string.translate)); builder.setMessage(finalString); builder.setCancelable(true); builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); //Toast.makeText(getActivity(), finalString, Toast.LENGTH_LONG).show(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.speed.traquer.app.TraqComplaintTaxi.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_traq_complaint_taxi); easyTracker = EasyTracker.getInstance(TraqComplaintTaxi.this); //onCreateView(savedInstanceState); //InitialSetupUI(); //Added UIHelper uiHelper = new UiLifecycleHelper(this, null); uiHelper.onCreate(savedInstanceState); inputTaxi = (EditText) findViewById(R.id.taxi_id); taxiDriver = (EditText) findViewById(R.id.taxi_driver); taxiLic = (EditText) findViewById(R.id.taxi_license); geoLat = (TextView) findViewById(R.id.geoLat); geoLong = (TextView) findViewById(R.id.geoLong); editDate = (EditText) findViewById(R.id.editDate); editTime = (EditText) findViewById(R.id.editTime); editCurrTime = (EditText) findViewById(R.id.editCurrTime); complainSend = (Button) findViewById(R.id.complain_send); ProgressBar barProgress = (ProgressBar) findViewById(R.id.progressLoading); ProgressBar barProgressFrom = (ProgressBar) findViewById(R.id.progressLoadingFrom); ProgressBar barProgressTo = (ProgressBar) findViewById(R.id.progressLoadingTo); actv_comp_taxi = (AutoCompleteTextView) findViewById(R.id.search_taxi_comp); SuggestionAdapter sa = new SuggestionAdapter(this, actv_comp_taxi.getText().toString(), taxiUrl, "compcode"); sa.setLoadingIndicator(barProgress); actv_comp_taxi.setAdapter(sa);/*from ww w . j ava 2 s .c o m*/ actv_from = (AutoCompleteTextView) findViewById(R.id.search_from); SuggestionAdapter saFrom = new SuggestionAdapter(this, actv_from.getText().toString(), locUrl, "location"); saFrom.setLoadingIndicator(barProgressFrom); actv_from.setAdapter(saFrom); actv_to = (AutoCompleteTextView) findViewById(R.id.search_to); SuggestionAdapter saTo = new SuggestionAdapter(this, actv_to.getText().toString(), locUrl, "location"); saTo.setLoadingIndicator(barProgressTo); actv_to.setAdapter(saTo); /*if(isNetworkConnected()) { new getTaxiComp().execute(new ApiConnector()); }*/ //Setting Fonts String fontPath = "fonts/segoeuil.ttf"; Typeface tf = Typeface.createFromAsset(getAssets(), fontPath); complainSend.setTypeface(tf); inputTaxi.setTypeface(tf); editDate.setTypeface(tf); editTime.setTypeface(tf); actv_comp_taxi.setTypeface(tf); actv_to.setTypeface(tf); actv_from.setTypeface(tf); taxiDriver.setTypeface(tf); taxiLic.setTypeface(tf); TextView txtComp = (TextView) findViewById(R.id.taxi_comp); txtComp.setTypeface(tf); TextView txtTaxiDriver = (TextView) findViewById(R.id.txt_taxi_driver); txtTaxiDriver.setTypeface(tf); TextView txtTaxiLic = (TextView) findViewById(R.id.txt_taxi_license); txtTaxiLic.setTypeface(tf); TextView txtNumber = (TextView) findViewById(R.id.taxi_number); txtNumber.setTypeface(tf); TextView txtTo = (TextView) findViewById(R.id.to); txtTo.setTypeface(tf); TextView txtDate = (TextView) findViewById(R.id.date); txtDate.setTypeface(tf); TextView txtTime = (TextView) findViewById(R.id.time); txtTime.setTypeface(tf); gLongitude = this.getIntent().getExtras().getDouble("Longitude"); gLatitude = this.getIntent().getExtras().getDouble("Latitude"); speedTaxiExceed = this.getIntent().getExtras().getDouble("SpeedTaxiExceed"); isTwitterSelected = false; isFacebookSelected = false; isDefaultSelected = false; isSmsSelected = false; geoLat.setText(Double.toString(gLatitude)); geoLong.setText(Double.toString(gLongitude)); rateBtnBus = (ImageButton) findViewById(R.id.btn_rate_bus); rateBtnBus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (actv_comp_taxi.length() != 0) { final AlertDialog.Builder alertBox = new AlertDialog.Builder(TraqComplaintTaxi.this); alertBox.setIcon(R.drawable.info_icon); alertBox.setCancelable(false); alertBox.setTitle("Do you want to cancel complaint?"); alertBox.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { // finish used for destroyed activity easyTracker.send(MapBuilder .createEvent("Complaint", "Cancel Complaint (Yes)", "Complaint event", null) .build()); finish(); } }); alertBox.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { easyTracker.send(MapBuilder .createEvent("Complaint", "Cancel Complaint (No)", "Complaint event", null) .build()); dialog.cancel(); } }); alertBox.show(); } else { Intent intent = new Intent(getApplicationContext(), TraqComplaint.class); intent.putExtra("Latitude", gLatitude); intent.putExtra("Longitude", gLongitude); intent.putExtra("SpeedBusExceed", speedTaxiExceed); startActivity(intent); } } }); complainSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String taxi_id = inputTaxi.getText().toString().toUpperCase(); String taxi_comp = actv_comp_taxi.getText().toString(); /*if(taxi_comp.length() == 0){ Toast.makeText(TraqComplaintTaxi.this, "Taxi Company is required!", Toast.LENGTH_SHORT).show(); }else */ if (taxi_comp.length() < 2) { Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Company.", Toast.LENGTH_SHORT).show(); } else if (taxi_id.length() == 0) { Toast.makeText(TraqComplaintTaxi.this, "Taxi Plate Number is required!", Toast.LENGTH_SHORT) .show(); } else if (taxi_id.length() < 7) { Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Number.", Toast.LENGTH_SHORT).show(); } else { easyTracker.send( MapBuilder.createEvent("Complaint", "Dialog Prompt", "Complaint event", null).build()); PromptCustomDialog(); } } }); setCurrentDateOnView(); getCurrentTime(); //Shi Chuan's Code StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); cd = new ConnectionDetector(getApplicationContext()); // Check if Internet present if (!cd.isConnectingToInternet()) { // Internet Connection is not present alert.showAlertDialog(TraqComplaintTaxi.this, "Internet Connection Error", "Please connect to working Internet connection", false); // stop executing code by return return; } // Check if twitter keys are set if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) { // Internet Connection is not present alert.showAlertDialog(TraqComplaintTaxi.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false); // stop executing code by return return; } // Shared Preferences mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0); /** This if conditions is tested once is * redirected from twitter page. Parse the uri to get oAuth * Verifier * */ if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { // oAuth verifier String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { // Get the access token AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); // Shared Preferences SharedPreferences.Editor e = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.commit(); // save changes Log.e("Twitter OAuth Token", "> " + accessToken.getToken()); // Getting user details from twitter // For now i am getting his name only long userID = accessToken.getUserId(); User user = twitter.showUser(userID); String username = user.getName(); String description = user.getDescription(); // Displaying in xml ui //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description)); } catch (Exception e) { // Check log for login errors Log.e("Twitter Login Error", "> " + e.getMessage()); } } } //LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); //LocationListener ll = new passengerLocationListener(); //lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); }
From source file:org.chromium.chrome.browser.ntp.snippets.SnippetArticleViewHolder.java
public void onBindViewHolder(SnippetArticle article) { super.onBindViewHolder(); mArticle = article;//from www .j a v a 2s .com updateLayout(); mHeadlineTextView.setText(mArticle.mTitle); // DateUtils.getRelativeTimeSpanString(...) calls through to TimeZone.getDefault(). If this // has never been called before it loads the current time zone from disk. In most likelihood // this will have been called previously and the current time zone will have been cached, // but in some cases (eg instrumentation tests) it will cause a strict mode violation. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); try { long time = SystemClock.elapsedRealtime(); CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString( mArticle.mPublishTimestampMilliseconds, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS); RecordHistogram.recordTimesHistogram("Android.StrictMode.SnippetUIBuildTime", SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS); // We format the publisher here so that having a publisher name in an RTL language // doesn't mess up the formatting on an LTR device and vice versa. String publisherAttribution = String.format(PUBLISHER_FORMAT_STRING, BidiFormatter.getInstance().unicodeWrap(mArticle.mPublisher), relativeTimeSpan); mPublisherTextView.setText(publisherAttribution); } finally { StrictMode.setThreadPolicy(oldPolicy); } // The favicon of the publisher should match the textview height. int widthSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); mPublisherTextView.measure(widthSpec, heightSpec); mPublisherFaviconSizePx = mPublisherTextView.getMeasuredHeight(); mArticleSnippetTextView.setText(mArticle.mPreviewText); // If there's still a pending thumbnail fetch, cancel it. cancelImageFetch(); // If the article has a thumbnail already, reuse it. Otherwise start a fetch. // mThumbnailView's visibility is modified in updateLayout(). if (mThumbnailView.getVisibility() == View.VISIBLE) { if (mArticle.getThumbnailBitmap() != null) { mThumbnailView.setImageBitmap(mArticle.getThumbnailBitmap()); } else { mThumbnailView.setImageResource(R.drawable.ic_snippet_thumbnail_placeholder); mImageCallback = new FetchImageCallback(this, mArticle); mNewTabPageManager.getSuggestionsSource().fetchSuggestionImage(mArticle, mImageCallback); } } // Set the favicon of the publisher. try { fetchFaviconFromLocalCache(new URI(mArticle.mUrl), true); } catch (URISyntaxException e) { setDefaultFaviconOnView(); } }
From source file:com.edible.ocr.CaptureActivity.java
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); checkFirstLaunch();/*from ww w . j av a 2 s . c o m*/ if (isFirstLaunch) { setDefaultPreferences(); } currentContext = this; Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.capture); viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view); cameraButtonView = findViewById(R.id.camera_button_view); resultView = findViewById(R.id.result_view); statusViewBottom = (TextView) findViewById(R.id.status_view_bottom); registerForContextMenu(statusViewBottom); statusViewTop = (TextView) findViewById(R.id.status_view_top); registerForContextMenu(statusViewTop); handler = null; lastResult = null; hasSurface = false; beepManager = new BeepManager(this); // Camera shutter button if (DISPLAY_SHUTTER_BUTTON) { shutterButton = (ShutterButton) findViewById(R.id.shutter_button); shutterButton.setOnShutterButtonListener(this); } settingButton = (Button) findViewById(R.id.setting_button); settingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(currentContext, PreferencesActivity.class); startActivity(intent); } }); aboutButton = (Button) findViewById(R.id.about_button); aboutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(currentContext, HelpActivity.class); intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, HelpActivity.ABOUT_PAGE); startActivity(intent); } }); final EditText editText = (EditText) findViewById(R.id.typed_result); editText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEARCH) { // add capture button function Intent openDetail = new Intent(currentContext, DetailInfo.class); String req = editText.getText().toString(); // openDetail.putExtra("request", "Filet Steak"); openDetail.putExtra("request", req); editText.setText(""); startActivity(openDetail); handled = true; } return handled; } }); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); //DB_textview = (TextView)findViewById(R.id.DB_text_view); //new HttpAsyncTask().execute("https://www.googleapis.com/language/translate/v2?key=" + KEY + "&q=hello%20world&source=en&target=de"); /* For Client Server Connection */ getButton = (Button) findViewById(R.id.get_text_button); getButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent openDetail = new Intent(currentContext, DetailInfo.class); String req = (String) ocrResultView.getText(); // openDetail.putExtra("request", "Filet Steak"); openDetail.putExtra("request", req); startActivity(openDetail); } }); ocrResultView = (TextView) findViewById(R.id.ocr_result_text_view); registerForContextMenu(ocrResultView); translationView = (TextView) findViewById(R.id.translation_text_view); registerForContextMenu(translationView); progressView = (View) findViewById(R.id.indeterminate_progress_indicator_view); cameraManager = new CameraManager(getApplication()); viewfinderView.setCameraManager(cameraManager); // Set listener to change the size of the viewfinder rectangle. viewfinderView.setOnTouchListener(new View.OnTouchListener() { int lastX = -1; int lastY = -1; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = -1; lastY = -1; return true; case MotionEvent.ACTION_MOVE: int currentX = (int) event.getX(); int currentY = (int) event.getY(); try { Rect rect = cameraManager.getFramingRect(); final int BUFFER = 50; final int BIG_BUFFER = 60; if (lastX >= 0) { // Adjust the size of the viewfinder rectangle. Check if the touch event occurs in the corner areas first, because the regions overlap. if (((currentX >= rect.left - BIG_BUFFER && currentX <= rect.left + BIG_BUFFER) || (lastX >= rect.left - BIG_BUFFER && lastX <= rect.left + BIG_BUFFER)) && ((currentY <= rect.top + BIG_BUFFER && currentY >= rect.top - BIG_BUFFER) || (lastY <= rect.top + BIG_BUFFER && lastY >= rect.top - BIG_BUFFER))) { // Top left corner: adjust both top and left sides cameraManager.adjustFramingRect(2 * (lastX - currentX), 2 * (lastY - currentY)); viewfinderView.removeResultText(); } else if (((currentX >= rect.right - BIG_BUFFER && currentX <= rect.right + BIG_BUFFER) || (lastX >= rect.right - BIG_BUFFER && lastX <= rect.right + BIG_BUFFER)) && ((currentY <= rect.top + BIG_BUFFER && currentY >= rect.top - BIG_BUFFER) || (lastY <= rect.top + BIG_BUFFER && lastY >= rect.top - BIG_BUFFER))) { // Top right corner: adjust both top and right sides cameraManager.adjustFramingRect(2 * (currentX - lastX), 2 * (lastY - currentY)); viewfinderView.removeResultText(); } else if (((currentX >= rect.left - BIG_BUFFER && currentX <= rect.left + BIG_BUFFER) || (lastX >= rect.left - BIG_BUFFER && lastX <= rect.left + BIG_BUFFER)) && ((currentY <= rect.bottom + BIG_BUFFER && currentY >= rect.bottom - BIG_BUFFER) || (lastY <= rect.bottom + BIG_BUFFER && lastY >= rect.bottom - BIG_BUFFER))) { // Bottom left corner: adjust both bottom and left sides cameraManager.adjustFramingRect(2 * (lastX - currentX), 2 * (currentY - lastY)); viewfinderView.removeResultText(); } else if (((currentX >= rect.right - BIG_BUFFER && currentX <= rect.right + BIG_BUFFER) || (lastX >= rect.right - BIG_BUFFER && lastX <= rect.right + BIG_BUFFER)) && ((currentY <= rect.bottom + BIG_BUFFER && currentY >= rect.bottom - BIG_BUFFER) || (lastY <= rect.bottom + BIG_BUFFER && lastY >= rect.bottom - BIG_BUFFER))) { // Bottom right corner: adjust both bottom and right sides cameraManager.adjustFramingRect(2 * (currentX - lastX), 2 * (currentY - lastY)); viewfinderView.removeResultText(); } else if (((currentX >= rect.left - BUFFER && currentX <= rect.left + BUFFER) || (lastX >= rect.left - BUFFER && lastX <= rect.left + BUFFER)) && ((currentY <= rect.bottom && currentY >= rect.top) || (lastY <= rect.bottom && lastY >= rect.top))) { // Adjusting left side: event falls within BUFFER pixels of left side, and between top and bottom side limits cameraManager.adjustFramingRect(2 * (lastX - currentX), 0); viewfinderView.removeResultText(); } else if (((currentX >= rect.right - BUFFER && currentX <= rect.right + BUFFER) || (lastX >= rect.right - BUFFER && lastX <= rect.right + BUFFER)) && ((currentY <= rect.bottom && currentY >= rect.top) || (lastY <= rect.bottom && lastY >= rect.top))) { // Adjusting right side: event falls within BUFFER pixels of right side, and between top and bottom side limits cameraManager.adjustFramingRect(2 * (currentX - lastX), 0); viewfinderView.removeResultText(); } else if (((currentY <= rect.top + BUFFER && currentY >= rect.top - BUFFER) || (lastY <= rect.top + BUFFER && lastY >= rect.top - BUFFER)) && ((currentX <= rect.right && currentX >= rect.left) || (lastX <= rect.right && lastX >= rect.left))) { // Adjusting top side: event falls within BUFFER pixels of top side, and between left and right side limits cameraManager.adjustFramingRect(0, 2 * (lastY - currentY)); viewfinderView.removeResultText(); } else if (((currentY <= rect.bottom + BUFFER && currentY >= rect.bottom - BUFFER) || (lastY <= rect.bottom + BUFFER && lastY >= rect.bottom - BUFFER)) && ((currentX <= rect.right && currentX >= rect.left) || (lastX <= rect.right && lastX >= rect.left))) { // Adjusting bottom side: event falls within BUFFER pixels of bottom side, and between left and right side limits cameraManager.adjustFramingRect(0, 2 * (currentY - lastY)); viewfinderView.removeResultText(); } } } catch (NullPointerException e) { Log.e(TAG, "Framing rect not available", e); } v.invalidate(); lastX = currentX; lastY = currentY; return true; case MotionEvent.ACTION_UP: lastX = -1; lastY = -1; return true; } return false; } }); isEngineReady = false; }
From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java
public void saveState() { // Temporarily allowing disk access. TODO: Fix. See http://b/5518024 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites(); try {/*w w w . j av a2 s. co m*/ long saveStateStartTime = SystemClock.uptimeMillis(); // The list of tabs should be saved first in case our activity is terminated early. // Explicitly toss out any existing SaveListTask because they only save the TabModel as // it looked when the SaveListTask was first created. if (mSaveListTask != null) mSaveListTask.cancel(true); try { saveListToFile(serializeTabMetadata()); } catch (IOException e) { Log.w(TAG, "Error while saving tabs state; will attempt to continue...", e); } logExecutionTime("SaveListTime", saveStateStartTime); // Add current tabs to save because they did not get a save signal yet. Tab currentStandardTab = TabModelUtils.getCurrentTab(mTabModelSelector.getModel(false)); if (currentStandardTab != null && !mTabsToSave.contains(currentStandardTab) && currentStandardTab.isTabStateDirty() // For content URI, the read permission granted to an activity is not // persistent. && !isTabUrlContentScheme(currentStandardTab)) { mTabsToSave.addLast(currentStandardTab); } Tab currentIncognitoTab = TabModelUtils.getCurrentTab(mTabModelSelector.getModel(true)); if (currentIncognitoTab != null && !mTabsToSave.contains(currentIncognitoTab) && currentIncognitoTab.isTabStateDirty() && !isTabUrlContentScheme(currentIncognitoTab)) { mTabsToSave.addLast(currentIncognitoTab); } // Wait for the current tab to save. if (mSaveTabTask != null) { // Cancel calls get() to wait for this to finish internally if it has to. // The issue is it may assume it cancelled the task, but the task still actually // wrote the state to disk. That's why we have to check mStateSaved here. if (mSaveTabTask.cancel(false) && !mSaveTabTask.mStateSaved) { // The task was successfully cancelled. We should try to save this state again. Tab cancelledTab = mSaveTabTask.mTab; if (!mTabsToSave.contains(cancelledTab) && cancelledTab.isTabStateDirty() && !isTabUrlContentScheme(cancelledTab)) { mTabsToSave.addLast(cancelledTab); } } mSaveTabTask = null; } long saveTabsStartTime = SystemClock.uptimeMillis(); // Synchronously save any remaining unsaved tabs (hopefully very few). for (Tab tab : mTabsToSave) { int id = tab.getId(); boolean incognito = tab.isIncognito(); try { TabState state = tab.getState(); if (state != null) { TabState.saveState(getTabStateFile(id, incognito), state, incognito); } } catch (OutOfMemoryError e) { Log.w(TAG, "Out of memory error while attempting to save tab state. Erasing."); deleteTabState(id, incognito); } } mTabsToSave.clear(); logExecutionTime("SaveTabsTime", saveTabsStartTime); logExecutionTime("SaveStateTime", saveStateStartTime); } finally { StrictMode.setThreadPolicy(oldPolicy); } }
From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java
public boolean modifyRelationship(int userId, Relationship.Action action) throws Exception { String actionString = ""; HashMap<String, Object> map = new HashMap<String, Object>(); HashMap<String, Object> args = new HashMap<String, Object>(); map.put("user_id", userId); switch (action) { case BLOCK://ww w .j ava 2 s . co m actionString = "block"; break; case UNBLOCK: actionString = "unblock"; break; case APPROVE: actionString = "approve"; break; case DENY: actionString = "deny"; break; case FOLLOW: actionString = "follow"; break; case UNFOLLOW: actionString = "unfollow"; break; } args.put("action", actionString); String uri = uriConstructor.constructUri(UriFactory.Relationships.MUTATE_RELATIONSHIP, map, true); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); PostMethod post = (new PostMethod(uri)).setPostParameters(args); JSONObject object = post.call().getJSON(); return object.getJSONObject("meta").getInt("code") == 200; }
From source file:itcr.gitsnes.MainActivity.java
/** The method sendGame makes many functions: * - Get all data from text boxes on layout add_game * - Makes a random bucket key for a photo/file and put the object into the bucket * - Wait for the success signal and send the JSON build from BackendHandler * to app-engine (Google)// w w w . j a v a 2 s . com */ public void sendGame(View view) throws IOException { Toast.makeText(this, "Wait, we are uploading your game =) ", Toast.LENGTH_LONG); /* GET DATA FROM INTERFACE*/ EditText name = (EditText) this.findViewById(R.id.txt_name); EditText description = (EditText) this.findViewById(R.id.txt_desc); EditText category = (EditText) this.findViewById(R.id.txt_cat); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); /* GENERATE RANDOM KEYS FOR PHOTO AND FILE*/ this.file_key = "" + UUID.randomUUID().toString().replace("-", ""); this.image_key = "" + UUID.randomUUID().toString().replace("-", ""); /* SAVING GAME FILE/PHOTO ON AWS BUCKET*/ AmazonS3Client s3Client = new AmazonS3Client( new BasicAWSCredentials(KS.MY_ACCESS_KEY_ID, KS.MY_SECRET_KEY)); PutObjectRequest putObjectRequestnew = new PutObjectRequest(KS.BUCKET_NAME, this.file_key, this.s3game); putObjectRequestnew.setCannedAcl(CannedAccessControlList.PublicRead); s3Client.putObject(putObjectRequestnew); PutObjectRequest putObjectImagenew = new PutObjectRequest(KS.BUCKET_IMG, this.image_key, this.s3image); putObjectImagenew.setCannedAcl(CannedAccessControlList.PublicRead); s3Client.putObject(putObjectImagenew); String actual_key = "none"; String actual_image = "none"; if (this.file_key != "none") actual_key = this.file_key; if (this.image_key != "none") actual_image = this.image_key; /* SEND JSON*/ new BackendHandler().sendJSON(KS.getCurrent_user(), name.getText().toString(), category.getText().toString(), description.getText().toString(), actual_image, actual_key); Log.i(TAG, "Successful JSON send"); Toast.makeText(this, "Congratulations your game has been sent", Toast.LENGTH_LONG); }
From source file:com.google.android.gms.samples.vision.ocrreader.MainActivity.java
/** * Called when an activity you launched exits, giving you the requestCode * you started it with, the resultCode it returned, and any additional * data from it. The <var>resultCode</var> will be * {@link #RESULT_CANCELED} if the activity explicitly returned that, * didn't return any result, or crashed during its operation. * <p/>//ww w . j av a2s . co m * <p>You will receive this call immediately before onResume() when your * activity is re-starting. * <p/> * * @param requestCode The integer request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode The integer result code returned by the child activity * through its setResult(). * @param data An Intent, which can return result data to the caller * (various data can be attached to Intent "extras"). * @see #startActivityForResult * @see #createPendingResult * @see #setResult(int) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { ocrDetect = 0; if (requestCode == RC_OCR_CAPTURE) { if (resultCode == CommonStatusCodes.SUCCESS) { if (data != null) { final String text = data.getStringExtra(OcrCaptureActivity.TextBlockObject); text1 = text; statusMessage.setText(R.string.ocr_success); MeterRdg.setVisibility(View.VISIBLE); MeterRdg.setText(text); if (MyMeter.isMeterOfType(SelectedCustomer.getMeter_type()) == 1) { MeterRdg.setEnabled(false); editRDG.setVisibility(View.VISIBLE); } // ok.setVisibility(View.VISIBLE); // ok.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // text1 = editText.getText().toString(); // textValue.setText(editText.getText()); // } // }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1); try { c = Calendar.getInstance(); _getLocation(); Reading readingNow = new Reading(custCode, MeterRdg.getText().toString()); readingNow.setDescription(Description.getText().toString()); request.addProperty("rdg_Value", readingNow.getRdg_value()); request.addProperty("rdg_Time", readingNow.getDateTime()); request.addProperty("Cst_ParCode", readingNow.getCst_ParCode()); request.addProperty("meterStatus", SelectedCustomer.getMeter_status()); //Declare the version of the SOAP request SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.setOutputSoapObject(request); envelope.dotNet = true; StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll() .build(); StrictMode.setThreadPolicy(policy); try { AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL); //this is the actual part that will call the webservice androidHttpTransport.call(SOAP_ACTION1, envelope); // Get the SoapResult from the envelope body. SoapPrimitive result = (SoapPrimitive) envelope.getResponse(); if (result.toString().equals("1")) { Toast.makeText(getApplicationContext(), " ", Toast.LENGTH_LONG) .show(); } else if (result.toString().equals("0")) { Toast.makeText(getApplicationContext(), " ", Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); Log.v("hihello", e.toString()); Toast.makeText(getApplicationContext(), " ? ? ", Toast.LENGTH_LONG).show(); serviceDB.InsertReading(readingNow); } } catch (Exception exception) { Toast.makeText(getApplicationContext(), " ", Toast.LENGTH_LONG).show(); } } }); Log.d(TAG, "Text read: " + text); } else { statusMessage.setText(R.string.ocr_failure); Log.d(TAG, "No Text captured, intent data is null"); } } else { statusMessage.setText(String.format(getString(R.string.ocr_error), CommonStatusCodes.getStatusCodeString(resultCode))); } } else { super.onActivityResult(requestCode, resultCode, data); } }
From source file:com.christophergs.mbientbasic.NavigationActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_navigation); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);/* w w w . j a v a2s.co m*/ /*CS comment: fab is the info button in bottom right */ FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ((ModuleFragmentBase) currentFragment).showHelpDialog(); ((ModuleFragmentBase) currentFragment2).showHelpDialog(); } }); /*CS comment: This creates the toggle "hamburger menu". Without it you have to drag the menu open and closed - not that obvious */ DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); /* CS comment: This listener basically gives the nav drawer life. Without it, the links don't do anything */ NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); if (savedInstanceState == null) { onNavigationItemSelected(navigationView.getMenu().findItem(R.id.nav_home)); } else { currentFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_KEY); } btDevice = getIntent().getParcelableExtra(EXTRA_BT_DEVICE); getApplicationContext().bindService(new Intent(this, MetaWearBleService.class), this, BIND_AUTO_CREATE); //DODGY HACK - SHOULD USE ASYNC TASK INSTEAD StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }