Example usage for android.os StrictMode setThreadPolicy

List of usage examples for android.os StrictMode setThreadPolicy

Introduction

In this page you can find the example usage for android.os StrictMode setThreadPolicy.

Prototype

public static void setThreadPolicy(final ThreadPolicy policy) 

Source Link

Document

Sets the policy for what actions on the current thread should be detected, as well as the penalty if such actions occur.

Usage

From source file:gob.sct.android.checatucell.services.LocationReceiver.java

@SuppressLint("NewApi")
@Override/*from  ww  w  . j  a v a2 s  . c  o  m*/
public void onTaskCompleted(int signalStrength) {
    operatorGsmSignalStrength = signalStrength;

    final String url = "http://ttr.sct.gob.mx/qoscell/web/QOSCSENALGEO/REGISTRO/SENAL.action?" + "dintensidad="
            + operatorGsmSignalStrength + ".0&tipo=0" + "&danchobanda=0&" + "dlatitud="
            + mLocation.getLatitude() + "&dlongitud=" + mLocation.getLongitude() + "&d_altitud="
            + mLocation.getAltitude() + "&dtipoconexiond=" + dataConnectionType + "&ioperador=" + idOperdador;

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    WebUtil.downloadPage(url);
    //      sendNotification(WebUtil.downloadPage(url));

    //      http://ttr.sct.gob.mx/qoscell/web/QOSCSENALGEO/REGISTRO/SENAL.action?dintensidad=1&tipo=1&danchobanda=1&dlatitud=1&dlongitud=1&d_altitud=1&dtipoconexiond=1&ioperador=1
}

From source file:com.ithinkbest.taipeiok.NavigationDrawerActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }//from w  w w  . j  ava 2  s  . co m
    // Handle action buttons
    switch (item.getItemId()) {
    //            case R.id.action_websearch:
    //                // create intent to perform web search for this planet
    //                Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
    //                intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
    //                // catch event that there's no activity to handle intent
    //                if (intent.resolveActivity(getPackageManager()) != null) {
    //                    startActivity(intent);
    //                } else {
    //                    Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
    //                }
    //                return true;
    case R.id.action_update:
        Log.d(LOG_TAG, "...DEBUG action_update");
        // use this to start and trigger a service
        Intent i = new Intent(getApplicationContext(), UpdateService.class);
        // potentially add data to the intent
        int[] cats = { 0, 1 };
        i.putExtra("CATS", cats);
        getApplicationContext().startService(i);

        return true;

    case R.id.action_del_all:
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        getContentResolver().delete(OkProvider.CONTENT_URI, null, null);
        return true;
    case R.id.action_debug:
        doingDebug();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.level28.android.moca.ui.MainActivity.java

/**
 * Setup {@link StrictMode} assertions in debug builds.
 *///from w  w  w.  jav a2s.c  om
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void setupStrictMode() {
    final ThreadPolicy.Builder threadPolicyBuilder = new ThreadPolicy.Builder();

    // StrictMode thread policy:
    threadPolicyBuilder.detectNetwork() // No network activity in UI thread
            .penaltyLog() // Log violations
            .penaltyDeath(); // Kill the process on violation
    StrictMode.setThreadPolicy(threadPolicyBuilder.build());

    /*
     * NOTE: we don't define a StrictMode VmPolicy because the Google Maps
     * API misbehaves *BADLY* and it will pollute the logs with heaps of
     * messages we can't do anything about. -morph
     */
    Log.i(LOG_TAG,
            "StrictMode enabled - Everyone, please observe that the \"fasten your seatbelt\" and \"no smoking\" signs have been turned on. Sit back and enjoy your flight.");
}

From source file:com.youku.player.base.YoukuBasePlayerActivity.java

/**
 * ?YoukuPlayersetIEncryptVideoCallBack?
 * YoukuBasePlayerActivity??call???//w w w  .  j av a 2s  .c  o  m
 */
//   public boolean isApiServiceAvailable = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    Logger.d("PlayFlow", "YoukuBasePlayerActivity->onCreate");
    if (DEVELOPER_MODE) {
        StrictMode.setThreadPolicy(
                new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // ??detectAll()
                        // ?I/O
                        .penaltyLog() // ?logcat??dropbox?log
                        .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() // SQLite???
                .penaltyLog() // ?logcat
                .penaltyDeath().build());
    }

    super.onCreate(savedInstanceState);
    /*      isApiServiceAvailable = PlayerUiUtile.isYoukuPlayerServiceAvailable(this);
            if(!isApiServiceAvailable){
             return;
          }
            
          PlayerUiUtile.initialYoukuPlayerService(this);
          mediaPlayerDelegate = RemoteInterface.mediaPlayerDelegate;*/

    if (mCreateTime == 0) {
        // ????
        Profile.getVideoQualityFromSharedPreferences(getApplicationContext());
    }
    ++mCreateTime;
    youkuContext = this;
    mImageWorker = (ImageResizer) getImageWorker(this);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    OfflineStatistics offline = new OfflineStatistics();
    offline.sendVV(this);

    ACTIVE_TIME = PreferenceUtil.getPreference(this, "active_time");
    if (ACTIVE_TIME == null || ACTIVE_TIME.length() == 0) {
        ACTIVE_TIME = String.valueOf(System.currentTimeMillis());
        PreferenceUtil.savePreference(this, "active_time", ACTIVE_TIME);
    }

    // ??
    Profile.GUID = Device.guid;
    try {
        YoukuBasePlayerActivity.versionName = getPackageManager().getPackageInfo(getPackageName(),
                PackageManager.GET_META_DATA).versionName;
    } catch (NameNotFoundException e) {
        YoukuBasePlayerActivity.versionName = "3.1";
        Logger.e(TAG_GLOBAL, e);
    }

    if (TextUtils.isEmpty(com.baseproject.utils.Profile.User_Agent)) {
        String plant = UIUtils.isTablet(this) ? "Youku HD;" : "Youku;";
        com.baseproject.utils.Profile.initProfile("player", plant + versionName + ";Android;"
                + android.os.Build.VERSION.RELEASE + ";" + android.os.Build.MODEL, getApplicationContext());
    }

    //      mApplication = PlayerApplication.getPlayerApplicationInstance();
    flags = getApplicationInfo().flags;
    com.baseproject.utils.Profile.mContext = getApplicationContext();
    if (MediaPlayerProxyUtil.isUplayerSupported()) { //-------------------->
        YoukuBasePlayerActivity.isHighEnd = true;
        // 
        PreferenceUtil.savePreference(this, "isSoftwareDecode", true);
        com.youku.player.goplay.Profile
                .setVideoType_and_PlayerType(com.youku.player.goplay.Profile.FORMAT_FLV_HD, this);
    } else {
        YoukuBasePlayerActivity.isHighEnd = false;
        com.youku.player.goplay.Profile
                .setVideoType_and_PlayerType(com.youku.player.goplay.Profile.FORMAT_3GPHD, this);
    }

    IMediaPlayerDelegate.is = getResources().openRawResource(R.raw.aes); //-------------------------------------->
    orientationHelper = new DeviceOrientationHelper(this, this);
}

From source file:jp.gr.java_conf.ya.shiobeforandroid3.UpdateTweetDrive.java

@Override
protected final void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
    }/*  w  ww . j a  v a 2  s. c  o  m*/

    simpleauth();

    crpKey = getString(R.string.app_name);
    final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    crpKey += telephonyManager.getDeviceId();
    crpKey += telephonyManager.getSimSerialNumber();
    try {
        final PackageInfo packageInfo = getPackageManager()
                .getPackageInfo("jp.gr.java_conf.ya.shiobeforandroid3", PackageManager.GET_META_DATA);
        crpKey += Long.toString(packageInfo.firstInstallTime);
    } catch (NameNotFoundException e) {
        WriteLog.write(this, e);
    }

    adapter = new ListAdapter(this, crpKey, null, null);

    setContentView(R.layout.tweet_drive);
    tableLayout1 = (TableLayout) this.findViewById(R.id.tableLayout1);
    editText2 = (EditText) this.findViewById(R.id.editText2);
    editText4 = (EditText) this.findViewById(R.id.editText4);
    editText5 = (EditText) this.findViewById(R.id.editText5);
    editText2.setFocusable(true);
    editText2.setFocusableInTouchMode(true);
    editText2.requestFocusFromTouch();

    pref_app = PreferenceManager.getDefaultSharedPreferences(this);

    final String pref_tl_fontfilename = pref_app.getString("pref_tl_fontfilename", "");
    if (pref_tl_fontfilename.equals("") == false) {
        try {
            WriteLog.write(this, "pref_tl_fontfilename: " + pref_tl_fontfilename);
            fontUtil.loadFont(pref_tl_fontfilename, this);

            fontUtil.setFont(editText2, this);
            fontUtil.setFont(editText4, this);
            fontUtil.setFont(editText5, this);
        } catch (final Exception e) {
            WriteLog.write(this, e);
        }
    }

    final float pref_tl_fontsize_updatetweet = ListAdapter.getPrefFloat(this, "pref_tl_fontsize_updatetweet",
            "14");
    editText2.setTextSize(pref_tl_fontsize_updatetweet);
    editText4.setTextSize(pref_tl_fontsize_updatetweet);
    editText5.setTextSize(pref_tl_fontsize_updatetweet);

    final String pref_tl_bgcolor_updatetweet = pref_app.getString("pref_tl_bgcolor_updatetweet", "#000000");
    pref_tl_fontcolor_text_updatetweet = pref_app.getString("pref_tl_fontcolor_text_updatetweet", "#ffffff");
    pref_tl_fontcolor_text_updatetweet_over = pref_app.getString("pref_tl_fontcolor_text_updatetweet_over",
            "#ff0000");

    if (pref_tl_bgcolor_updatetweet.equals("") == false) {
        try {
            tableLayout1.setBackgroundColor(Color.parseColor(pref_tl_bgcolor_updatetweet));
        } catch (final IllegalArgumentException e) {
        }
    }
    setTextColorOnTextChanged();
    if (pref_tl_fontcolor_text_updatetweet.equals("") == false) {
        try {
            editText4.setTextColor(Color.parseColor(pref_tl_fontcolor_text_updatetweet));
            editText5.setTextColor(Color.parseColor(pref_tl_fontcolor_text_updatetweet));
        } catch (final IllegalArgumentException e) {
        }
    }

    editText2.addTextChangedListener(new TextWatcher() {
        @Override
        public final void afterTextChanged(final Editable s) {
            setTextColorOnTextChanged();
        }

        @Override
        public final void beforeTextChanged(final CharSequence s, final int start, final int count,
                final int after) {
        }

        @Override
        public final void onTextChanged(final CharSequence s, final int start, final int before,
                final int count) {
            setTextColorOnTextChanged();
        }
    });
    editText2.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public final void onFocusChange(final View arg0, final boolean arg1) {
            setTextColorOnTextChanged();
        }
    });

    editText2.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public final boolean onLongClick(final View v) {
            tweet();
            return true;
        }
    });

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

    final String pref_map_site = pref_app.getString("pref_map_site", "0");
    if (pref_map_site.equals("0")) {
        try {
            MapsInitializer.initialize(this);
        } catch (final Exception e) {
            toast("You must update Google Google Play Service.");
        }
    } else {
        try {
            map.setMapType(GoogleMap.MAP_TYPE_NONE);

            final TileProvider tileProvider = new UrlTileProvider(256, 256) {
                @Override
                public final synchronized URL getTileUrl(final int x, final int y, final int zoom) {
                    // The moon tile coordinate system is reversed.  This is not normal.
                    // int reversedY = (1 << zoom) - y - 1;
                    // String s = String.format(Locale.US, MOON_MAP_URL_FORMAT, zoom, x, reversedY);
                    final String s = String.format(Locale.US,
                            ((pref_map_site.equals("0")) ? ListAdapter.OSM_MAP_URL_FORMAT
                                    : ListAdapter.GSI_MAP_URL_FORMAT),
                            zoom, x, y);
                    URL url = null;
                    try {
                        url = new URL(s);
                    } catch (final MalformedURLException e) {
                        throw new AssertionError(e);
                    }
                    return url;
                }
            };

            map.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
        } catch (final Exception e) {
            try {
                MapsInitializer.initialize(this);
            } catch (final Exception e1) {
                toast("You must update Google Maps.");
            }
        }
    }

    moveTo(35.66279, 139.759848, 0.0f, 0.0f);
}

From source file:com.android.projectz.teamrocket.thebusapp.activities.SplashScreenActivity.java

/**
 * permette di capire se il server esterno  attualmente disponibile oppure  offline
 *
 * @return boolean che identifica se il server  online o offline
 *//*from  w w  w .  j  ava 2 s .  co m*/
private boolean checkConnectionToServer() {
    if (android.os.Build.VERSION.SDK_INT > 9) { //questo per i permessi OBBLIGATORIO
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    URL url = null;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(SharedPreferencesUtils.getWebsiteUrl(this) + "/app/altra_prova.php");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            urlConnection.disconnect();
            return true;
        }
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        if (!SharedPreferencesUtils.getWebsiteUrl(this).equals("http://thebusapp.orgfree.com")) {
            urlConnection.disconnect();
            SharedPreferencesUtils.setWebsiteUrl(this, "http://thebusapp.orgfree.com");
            checkConnectionToServer();
        }
        return false;
    }
}

From source file:com.fbbackup.MyFriendFragmentActivity.java

@SuppressLint("NewApi")
public void setLisetner() {

    // Tag//from   w  ww .  ja v a  2  s . c o m
    btn_tag_me.setOnClickListener(new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Fragment newFragment = new TagMeImageGridFragment();

            Bundle args = new Bundle();
            args.putString("token", token);
            args.putStringArray("tagMePicture", tagMePicture);
            args.putString("userName", friendsName[0]);

            newFragment.setArguments(args);

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.rl_user_photo, newFragment, "first");
            ft.addToBackStack(null);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            ft.commit();

            controlPanelHandler.sendEmptyMessage(HIDE_CONTROL_PANEL);
        }

    });

    btn_cancel_download.setOnClickListener(new ImageButton.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            downloadTask.cancel(true);
            downloadTaskNoUI.cancel(true);
            rl_prb_download.setVisibility(View.GONE);
            hasCancel = true;
        }

    });

    // Photo
    btn_photo.setOnClickListener(new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Fragment newFragment = new MyFriendFragment();

            Bundle args = new Bundle();
            args.putStringArray("friendPic", friendsPicture);
            args.putStringArray("friendName", friendsName);
            args.putStringArray("friendID", friendsID);
            args.putString("token", token);

            newFragment.setArguments(args);

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.rl_user_photo, newFragment, "first");

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            ft.commit();

        }
    });

    btn_logout.setOnClickListener(new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads()
                        .detectDiskWrites().detectNetwork() // or
                        // .detectAll()
                        // for
                        // all
                        // detectable
                        // problems
                        .penaltyLog().build());
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                        .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

            }

            try {
                facebook.logout(MyFriendFragmentActivity.this);

                Toast.makeText(MyFriendFragmentActivity.this, "FB logout", Toast.LENGTH_LONG).show();

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            SharedPreferences mPrefs = getSharedPreferences(MainActivity.FIRST_LOGIN_PREFERENCE, MODE_PRIVATE);

            Log.w("Ryan", "S:" + mPrefs.getBoolean(MainActivity.FIRST_LOGIN, true));

            SharedPreferences.Editor editor = mPrefs.edit();
            editor.putBoolean(MainActivity.FIRST_LOGIN, true);
            editor.commit();

            Log.w("Ryan", "F:" + mPrefs.getBoolean(MainActivity.FIRST_LOGIN, true));

            Intent it = new Intent();
            it.setClass(MyFriendFragmentActivity.this, MainActivity.class);
            startActivity(it);
            finish();

        }

    });
}

From source file:com.team08storyapp.ESHelper.java

/**
 * Returns a list of all Story objects contained on the webservice. These
 * stories can be used to display a list of all possible stories to view
 * online.//from  w  ww .j a va 2  s.  c  o m
 * 
 * @return The List of Stories from the webservice.
 * @see Story
 */
public ArrayList<Story> getOnlineStories() {
    /*
     * set policy to allow for internet activity to happen within the
     * android application
     */
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    ArrayList<Story> stories = new ArrayList<Story>();
    try {
        /*
         * Create a HttpPost object to retrieve the Stories from the
         * webservice
         */
        HttpPost postRequest = new HttpPost(
                "http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/_search?pretty=1&fields=onlineStoryId,title,author");

        /*
         * Set the httppost so that it knows it is retrieving a JSON
         * formatted object
         */
        postRequest.addHeader("Accept", "application/json");

        /* Execute the httpclient to get the object from the webservice */
        HttpResponse response = httpclient.execute(postRequest);

        /* Retrieve and print to the log cat the status result of the post */
        String status = response.getStatusLine().toString();
        Log.d(TAG, status);

        /*
         * Retrieve the Story object in the form of a string to be converted
         * from JSON
         */
        String json = getEntityContent(response);

        /* We have to tell GSON what type we expect */
        Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<Story>>() {
        }.getType();
        /* Now we expect to get a story response */
        ElasticSearchSearchResponse<Story> esResponse = gson.fromJson(json, elasticSearchSearchResponseType);
        /* We get the story from it! */
        Log.d(TAG, esResponse.toString());
        for (ElasticSearchResponse<Story> s : esResponse.getHits()) {
            Story story = s.getFields();
            stories.add(story);
        }

    } catch (ClientProtocolException e) {
        Log.d(TAG, e.getLocalizedMessage());
        return null;

    } catch (IOException e) {
        Log.d(TAG, e.getLocalizedMessage());
        return null;
    }
    return stories;
}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

private void updateUserContacts() {

    System.out.println("User_mobile_no ==" + selfNumber);

    signUpProcess = "com.roamprocess1.roaming4world.signUpProcess";
    prefSignUpProcess = prefs.getString(signUpProcess, "NotCompleted");

    allContactsCursor = ContactsWrapper.getInstance().getContactsPhones(mcontext, null);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    getAllContacts = fetch_contact_list(allContactsCursor);
    r4wContactListName = Arrays.asList(phoneContacts);
    r4wContactListName.size();/*from w w w .  j  a  v  a  2  s  .  c om*/
    if (prefSignUpProcess.equals("NotCompleted")) {
        defaultPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        System.out.println("defaultPath:" + defaultPath);
        System.out.println("selfNumber:" + selfNumber);

        try {
            contactFile = new File(defaultPath, selfNumber + ".txt");
            if (contactFile.exists()) {
                contactFile.delete();
                System.out.println("file Exist");
                sendContacts(contactFile);

            } else {
                System.out.println("file does not Exist");
                sendContacts(contactFile);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

}

From source file:itcr.gitsnes.MainActivity.java

/**
 *  Method to go mainFrame/*from   w  ww .j av  a2  s.com*/
 */
public void back_stage() {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    String input = new BackendHandler().readJSON();
    try {
        json_arr = new JSONArray(input);
    } catch (JSONException e) {
        Log.i(TAG, e.toString());
        Log.i(TAG, e.toString());
    }

    RelativeLayout rl = (RelativeLayout) this.findViewById(R.id.mainback);
    rl.setBackgroundColor(Color.parseColor("#009f28"));
    authButton.setVisibility(View.INVISIBLE);
    MasterGames new_fragment = new MasterGames(json_arr);
    new_fragment.setQtype("all");

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.placeholder, new_fragment);
    transaction.addToBackStack(null);
    transaction.commit();

}