List of usage examples for android.os StrictMode setThreadPolicy
public static void setThreadPolicy(final ThreadPolicy policy)
From source file:co.beem.project.beem.FbTextService.java
/** * {@inheritDoc}//ww w .ja v a 2 s.c om */ @Override public void onCreate() { super.onCreate(); Utils.setContext(getApplicationContext()); smackAndroid = SmackAndroid.init(FbTextService.this); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); savingMessageQueue = new LinkedBlockingQueue<co.beem.project.beem.service.BeemMessage>(); stateChangeQueue = new LinkedBlockingQueue<User>(); sendImageQueue = new LinkedBlockingDeque<ImageMessageInQueue>(); isRunning = true; sessionManager = new SessionManager(FbTextService.this); savingMessageOnBackgroundThread(new SavingNewMessageTask()); savingMessageOnBackgroundThread(new UpdateUserStateTask()); savingMessageOnBackgroundThread(new SendImageTask()); handler = new Handler(); registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTED)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTING)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_DISCONNECT)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTING_In)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.SEND_IMAGE_MESSAGE)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.SEND_INVITATION)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.UPDATE_USER_STATE)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.PUSH_NOTIFICATION_FAVORITE_ONLINE)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.CHANGE_STATUS)); mSettings = PreferenceManager.getDefaultSharedPreferences(this); mSettings.registerOnSharedPreferenceChangeListener(mPreferenceListener); if (mSettings.getBoolean(FbTextApplication.USE_AUTO_AWAY_KEY, false)) { mOnOffReceiverIsRegistered = true; registerReceiver(mOnOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); registerReceiver(mOnOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); // registerReceiver(sma, filter) } String tmpJid = mSettings.getString(FbTextApplication.ACCOUNT_USERNAME_KEY, "").trim(); mLogin = StringUtils.parseName(tmpJid); boolean useSystemAccount = mSettings.getBoolean(FbTextApplication.USE_SYSTEM_ACCOUNT_KEY, false); mPort = DEFAULT_XMPP_PORT; mService = StringUtils.parseServer(tmpJid); mHost = mService; initMemorizingTrustManager(); if (mSettings.getBoolean(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_KEY, false)) { mHost = mSettings.getString(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_HOST_KEY, "").trim(); if ("".equals(mHost)) mHost = mService; String tmpPort = mSettings.getString(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_PORT_KEY, "5222"); if (!"".equals(tmpPort)) mPort = Integer.parseInt(tmpPort); } if (mSettings.getBoolean(FbTextApplication.FULL_JID_LOGIN_KEY, false) || "gmail.com".equals(mService) || "googlemail.com".equals(mService) || useSystemAccount) { mLogin = tmpJid; } configure(ProviderManager.getInstance()); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Roster.setDefaultSubscriptionMode(SubscriptionMode.manual); mBind = new XmppFacade(this); if (FbTextApplication.isDebug) Log.d(TAG, "Create FacebookTextService \t id: " + mLogin + " \t host: " + mHost + "\tmPort" + mPort + "\t service" + mService); }
From source file:com.dwdesign.tweetings.fragment.StatusFragment.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.j a va2s. co 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:org.chromium.chrome.browser.customtabs.CustomTabActivity.java
/** * Opens the URL currently being displayed in the Custom Tab in the regular browser. * @param forceReparenting Whether tab reparenting should be forced for testing. * * @return Whether or not the tab was sent over successfully. */// ww w .jav a 2s . c om boolean openCurrentUrlInBrowser(boolean forceReparenting) { Tab tab = getActivityTab(); if (tab == null) return false; String url = tab.getUrl(); if (DomDistillerUrlUtils.isDistilledPage(url)) { url = DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl(url); } if (TextUtils.isEmpty(url)) url = getUrlToLoad(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(ChromeLauncherActivity.EXTRA_IS_ALLOWED_TO_RETURN_TO_PARENT, false); boolean willChromeHandleIntent = getIntentDataProvider().isOpenedByChrome(); StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); StrictMode.allowThreadDiskWrites(); try { willChromeHandleIntent |= ExternalNavigationDelegateImpl.willChromeHandleIntent(this, intent, true); } finally { StrictMode.setThreadPolicy(oldPolicy); } Bundle startActivityOptions = ActivityOptionsCompat .makeCustomAnimation(this, R.anim.abc_fade_in, R.anim.abc_fade_out).toBundle(); if (willChromeHandleIntent || forceReparenting) { Runnable finalizeCallback = new Runnable() { @Override public void run() { finishAndClose(); } }; mMainTab = null; tab.detachAndStartReparenting(intent, startActivityOptions, finalizeCallback); } else { // Temporarily allowing disk access while fixing. TODO: http://crbug.com/581860 StrictMode.allowThreadDiskReads(); StrictMode.allowThreadDiskWrites(); try { startActivity(intent, startActivityOptions); } finally { StrictMode.setThreadPolicy(oldPolicy); } } return true; }
From source file:it.polimi.deib.p2pchat.discovery.chatmessages.waitingtosend.discovery.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //FIXME TODO TODO FIXME //this is a temporary quick fix for Android N developer preview //use the strict mode with permit all is absolutely a bad practice, //but at the moment there is an open issue (not fixed) reported to google. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); //----------------------------------------- setContentView(R.layout.main);// w ww. j a va2s.co m //activate the wakelock getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); this.setupToolBar(); intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(this, getMainLooper(), null); tabFragment = TabFragment.newInstance(); this.getSupportFragmentManager().beginTransaction().replace(R.id.container_root, tabFragment, "tabfragment") .commit(); this.getSupportFragmentManager().executePendingTransactions(); }
From source file:org.mozilla.gecko.BrowserApp.java
/** * Check and show the firstrun pane if the browser has never been launched and * is not opening an external link from another application. * * @param context Context of application; used to show firstrun pane if appropriate * @param intent Intent that launched this activity */// w ww . j a va 2s .c om private void checkFirstrun(Context context, SafeIntent intent) { if (intent.getBooleanExtra(EXTRA_SKIP_STARTPANE, false)) { // Note that we don't set the pref, so subsequent launches can result // in the firstrun pane being shown. return; } final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads(); try { final SharedPreferences prefs = GeckoSharedPrefs.forProfile(this); if (prefs.getBoolean(FirstrunPane.PREF_FIRSTRUN_ENABLED, false)) { if (!Intent.ACTION_VIEW.equals(intent.getAction())) { showFirstrunPager(); } // Don't bother trying again to show the v1 minimal first run. prefs.edit().putBoolean(FirstrunPane.PREF_FIRSTRUN_ENABLED, false).apply(); } } finally { StrictMode.setThreadPolicy(savedPolicy); } }
From source file:com.ibm.watson.developer_cloud.android.examples.IBMSpeechToText.java
/** public static class TTSCommands extends AsyncTask<Void, Void, JSONObject> { /*from w w w.j a va 2s . c o m*/ protected JSONObject doInBackground(Void... none) { return TextToSpeech.sharedInstance().getVoices(); } }*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); StorageReference mStorageRef; mStorageRef = FirebaseStorage.getInstance().getReference(); // Strictmode needed to run the http/wss request for devices > Gingerbread if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } //setContentView(R.layout.activity_main); setContentView(R.layout.activity_tab_text); ActionBar action = getActionBar(); action.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); tabSTT = action.newTab().setText("Meeting Recorder"); // tabTTS = actionBar.newTab().setText("Text to Speech"); tabSTT.setTabListener(new MyTabListener(fragmentTabSTT)); // tabTTS.setTabListener(new MyTabListener(fragmentTabTTS)); action.addTab(tabSTT); // actionBar.addTab(tabTTS); //actionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#B5C0D0"))); }
From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java
/** * If a global max tab ID has not been computed and stored before, then check all the state * folders and calculate a new global max tab ID to be used. Must be called before any new tabs * are created.// w w w . jav a2 s.co m * * @throws IOException */ private void checkAndUpdateMaxTabId() throws IOException { if (mPreferences.getBoolean(PREF_HAS_COMPUTED_MAX_ID, false)) return; int maxId = 0; // Calculation of the max tab ID is done only once per user and is stored in // SharedPreferences afterwards. This is done on the UI thread because it is on the // critical patch to initializing the TabIdManager with the correct max tab ID. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); try { File[] subDirectories = getOrCreateBaseStateDirectory().listFiles(); if (subDirectories != null) { for (File subDirectory : subDirectories) { if (!subDirectory.isDirectory()) { assert false : "Only directories should exist below the base state directory"; continue; } File[] files = subDirectory.listFiles(); if (files == null) continue; for (File file : files) { Pair<Integer, Boolean> tabStateInfo = TabState.parseInfoFromFilename(file.getName()); if (tabStateInfo != null) { maxId = Math.max(maxId, tabStateInfo.first); } else if (isStateFile(file.getName())) { DataInputStream stream = null; try { stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); maxId = Math.max(maxId, readSavedStateFile(stream, null, null, false)); } finally { StreamUtil.closeQuietly(stream); } } } } } } finally { StrictMode.setThreadPolicy(oldPolicy); } TabIdManager.getInstance().incrementIdCounterTo(maxId); mPreferences.edit().putBoolean(PREF_HAS_COMPUTED_MAX_ID, true).apply(); }
From source file:org.mozilla.gecko.GeckoApp.java
/** * Enable Android StrictMode checks (for supported OS versions). * http://developer.android.com/reference/android/os/StrictMode.html *//* w w w .j av a 2s.co m*/ private void enableStrictMode() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { return; } StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build()); }
From source file:com.mobiletin.inputmethod.indic.LatinIME.java
public void goForOnlineSuggetions(String url) { //Parse Method of Online Suggestion String zWord = ""; String mSugestion = ""; String mTargetWord = ""; if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }//from w w w. j a v a 2 s . c o m if (downloadFile(url)) { String jsonString = readTxtFile(); try { JSONArray jsonArray = new JSONArray(jsonString); if (jsonArray.length() > 0) { JSONArray jsonArray2 = jsonArray.getJSONArray(1); JSONArray jsonArray3 = jsonArray2.getJSONArray(0); for (int i = 0; i < jsonArray3.length(); i++) { if (i == 0) { zWord = jsonArray3.getString(i); // Log.e("ZWord", i + "=" + zWord); } else if (i == 1) { String ZWord = jsonArray3.getString(i); ZWord = ZWord.replaceAll("\\[", "").replaceAll("\\]", ""); ZWord = ZWord.replaceAll("\"", "").replaceAll("\"", ""); mSugestion = ZWord; // Log.e("suggestion---", mSugestion); String[] wordsArray = mSugestion.split(","); for (int z = 0; z < wordsArray.length; z++) { if (z == 0 /*(wordsArray.length - 1)*/) { mTargetWord = wordsArray[z]; //Log.e("TargetWord", i + "=" + mTargetWord); } } } else { break; } } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Insert Suggestion inDB if (zWord.length() > 0 && !zWord.isEmpty() && !mTargetWord.isEmpty()) { DBDictionary dbManager = new DBDictionary(this); DictionaryModel suggestionModel = new DictionaryModel(); suggestionModel.setSUGGESTIONS(mSugestion); suggestionModel.setTARGETWORD(mTargetWord); suggestionModel.setZWORD(zWord); dbManager.insertSuggestion(suggestionModel); } } }
From source file:com.example.sensingapp.SensingApp.java
/** Called when the activity is first created. */ @Override//from www . j a va 2 s . com public void onCreate(Bundle savedInstanceState) { int i; Location location = null; super.onCreate(savedInstanceState); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } try { Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { e.printStackTrace(); } m_smSurScan = (SensorManager) getSystemService(SENSOR_SERVICE); PackageManager pm = getPackageManager(); m_riHome = pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0); m_nBufferSize = AudioRecord.getMinBufferSize(m_nAudioSampleRate, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT); m_tmCellular = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); checkSensorAvailability(); //Get Existing Project Name and Existing User Name preconfigSetting(); /* When the power button is pressed and the screen goes off, the sensors will stop work by default, * Here keep the CPU on to keep sensor alive and also use SCREEN_OFF notification to re-enable GPS/WiFi */ PowerManager pwrManager = (PowerManager) getSystemService(Context.POWER_SERVICE); m_wakeLock = pwrManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(m_ScreenOffReceiver, filter); show_screen1(); }