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:ca.ualberta.cmput301f12t05.ufill.Webservicer.java

/**
 * Consumes the REMOVE operation of the service
 * Once a local bin has been deleted, it is removed from the webservice as well.
 * /*from   w w w. ja v  a2  s .  c  o m*/
 * @return void
 * @throws Exception
 */
public void removeBin(String SourcerId) throws Exception {
    List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    nvps.add(new BasicNameValuePair("action", "remove"));
    nvps.add(new BasicNameValuePair("id", SourcerId));

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    HttpResponse response = httpclient.execute(httpPost);

    String status = response.getStatusLine().toString();
    HttpEntity entity = response.getEntity();

    System.out.println(status);

    entity.consumeContent();
}

From source file:com.footprint.cordova.plugin.localnotification.Options.java

/**
 * Converts an Image URL to Bitmap.//from  w  ww.j  a v  a 2s . c  o  m
 *
 * @param src
 *      The external image URL
 * @return
 *      The corresponding bitmap
 */
private Bitmap getIconFromURL(String src) {
    Bitmap bmp = null;
    ThreadPolicy origMode = StrictMode.getThreadPolicy();

    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);

        connection.setDoInput(true);
        connection.connect();

        InputStream input = connection.getInputStream();

        bmp = BitmapFactory.decodeStream(input);
    } catch (Exception e) {
        e.printStackTrace();
    }

    StrictMode.setThreadPolicy(origMode);

    return bmp;
}

From source file:com.team08storyapp.ESHelper.java

/**
 * Returns a Story object for a specific onlineStoryId contained on the
 * webservice. This Story object can be used to display a
 * "Chose Your Own Adventure story"./*from w  w w.  ja  va  2s. co m*/
 * <p>
 * The method uses ElisticSearch (@link http://www.elasticsearch.org/guide/)
 * to retrieve the story from the webservice.
 * 
 * @param storyId
 *            The onlineStoryId of the Story to retrieve from the
 *            webservice.
 * @return The Story object for a specified onlineStoryId.
 * @see Story
 */
public Story getOnlineStory(int storyId) {
    /*
     * 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);

    Story story;
    try {
        /*
         * Create a HttpGet object with the onlineStoryId of the Story to
         * retrieve from the webservice
         */
        HttpGet getRequest = new HttpGet(
                "http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/" + storyId + "?pretty=1");

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

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

        /* 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 elasticSearchResponseType = new TypeToken<ElasticSearchResponse<Story>>() {
        }.getType();

        /* Now we expect to get a Story response */
        ElasticSearchResponse<Story> esResponse = gson.fromJson(json, elasticSearchResponseType);

        /* We get the Story from it! */
        story = esResponse.getSource();

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

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

    return story;
}

From source file:android.webkit.cts.WebViewTest.java

private void stopWebServer() throws Exception {
    assertNotNull(mWebServer);//from  ww  w  .  j a v a 2  s  .com
    ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
    ThreadPolicy tmpPolicy = new ThreadPolicy.Builder(oldPolicy).permitNetwork().build();
    StrictMode.setThreadPolicy(tmpPolicy);
    mWebServer.shutdown();
    mWebServer = null;
    StrictMode.setThreadPolicy(oldPolicy);
}

From source file:com.commonsware.empub.EmPubActivity.java

@TargetApi(9)
private void enableStrictMode() {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
}

From source file:com.yunluo.android.arcadehub.GameListActivity.java

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

    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    getScreenSize();//from  ww w. j  a va 2  s  .  co m

    init();

    initSliding();

    addSearchView();

    mApp.register();

    initPush();

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

}

From source file:org.zoumbox.mh_dla_notifier.Receiver.java

@Override
public void onReceive(Context context, Intent intent) {

    String intentAction = intent.getAction();
    Log.d(TAG, String.format("<<< %s#onReceive action=%s", getClass().getName(), intentAction));

    boolean connectivityChanged = ConnectivityManager.CONNECTIVITY_ACTION.equals(intentAction);
    boolean justGotConnection = false;
    if (connectivityChanged) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

        justGotConnection = activeNetwork != null && activeNetwork.isConnected();
        Log.d(TAG, "Connectivity change. isConnected=" + justGotConnection);
    }//from  w w w  . jav  a  2  s .co  m

    if (connectivityChanged && !justGotConnection) {
        Log.d(TAG, "Just lost connectivity, nothing to do");
        return;
    }

    String trollId = intent.getStringExtra(Alarms.EXTRA_TROLL_ID);
    if (Strings.isNullOrEmpty(trollId)) {
        Set<String> trollIds = getProfileProxy().getTrollIds(context);
        if (trollIds.isEmpty()) {
            Log.d(TAG, "No troll registered, exiting...");
            return;
        }
        trollId = trollIds.iterator().next();
        Log.d(TAG, "TrollId not defined, using the fist one: " + trollId);
    }

    if (!getProfileProxy().isPasswordDefined(context, trollId)) {
        Log.d(TAG, "Troll password is not defined, exiting...");
        return;
    }

    // If type is provided, request for an update
    String type = intent.getStringExtra(Alarms.EXTRA_TYPE);
    boolean requestUpdate = !Strings.isNullOrEmpty(type);

    // If device just started, request for wakeups registration
    boolean requestAlarmRegistering = justRestarted().apply(context);

    // Just go the internet connection back. Update will be necessary if
    //  - device restarted since last update and last update in more than 2 hours ago
    //  - last update failed because of network error
    if (!requestUpdate && justGotConnection) { // !requestUpdate because no need to check if update is already requested
        requestUpdate = Predicates
                .or(shouldUpdateBecauseOfRestart(trollId), shouldUpdateBecauseOfNetworkFailure(trollId))
                .apply(context);
    }

    Log.d(TAG, String.format("requestUpdate=%b ; requestAlarmRegistering=%b", requestUpdate,
            requestAlarmRegistering));

    // FIXME AThimel 14/02/14 Remove ASAP
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    try {
        Troll troll = getProfileProxy().fetchTrollWithoutUpdate(context, trollId).left();
        if (requestUpdate) {
            // If the current DLA already has no more PA, skip update
            boolean skipUpdate = false;
            if (AlarmType.CURRENT_DLA.name().equals(type)) {
                skipUpdate = troll.getPa() == 0 && MhDlaNotifierUtils.IS_IN_THE_FUTURE.apply(troll.getDla());
            }
            if (skipUpdate) {
                trollLoaded(troll, context, false);
            } else {
                refreshDla(context, trollId);
            }
        } else if (requestAlarmRegistering) {
            trollLoaded(troll, context, false);
        } else {
            Log.d(TAG, "Skip loading Troll");
        }
    } catch (MissingLoginPasswordException mde) {
        Log.w(TAG, "Missing trollId and/or password, exiting...");
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MyPageFragment.java

public ArrayList<ParentObject> fetchMyPage() {
    BarentswatchApi barentswatchApi = new BarentswatchApi();
    barentswatchApi.setAccesToken(user.getToken());

    if (!barentswatchApi.isTargetProd()) {
        Toast.makeText(getActivity(), "Targeting pilot environment", Toast.LENGTH_LONG).show();
    }//from  w w  w .  ja  va  2 s. c  om

    ArrayList<ParentObject> parentObjectList = new ArrayList<>();
    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        List<PropertyDescription> availableSubscriptions = barentswatchApi.getApi().getSubscribable();
        List<Subscription> currentSubscriptions = barentswatchApi.getApi().getSubscriptions();
        List<Authorization> authorizations = barentswatchApi.getApi().getAuthorization();
        Map<Integer, Boolean> authMap = new HashMap<>();
        Map<String, PropertyDescription> availableSubscriptionsMap = new HashMap<>();
        Map<String, Subscription> activeSubscriptionsMap = new HashMap<>();
        ArrayList<Object> availableSubscriptionObjectsList = new ArrayList<>();

        for (Authorization auth : authorizations) {
            authMap.put(auth.Id, auth.HasAccess);
        }

        for (Subscription subscription : currentSubscriptions) {
            activeSubscriptionsMap.put(subscription.GeoDataServiceName, subscription);
        }

        for (PropertyDescription subscribable : availableSubscriptions) {
            availableSubscriptionsMap.put(subscribable.ApiName, subscribable);
            SubscriptionEntry currentEntry = user.getSubscriptionCacheEntry(subscribable.ApiName);

            if (currentEntry == null) {
                SubscriptionEntry entry = activeSubscriptionsMap.get(subscribable.ApiName) == null
                        ? new SubscriptionEntry(subscribable, authMap.get(subscribable.Id))
                        : new SubscriptionEntry(subscribable, activeSubscriptionsMap.get(subscribable.ApiName),
                                authMap.get(subscribable.Id));
                entry.mIsAuthorized = authMap.get(subscribable.Id);
                user.setSubscriptionCacheEntry(subscribable.ApiName, entry);
            } else {
                currentEntry.mSubscribable = subscribable;
                currentEntry.mSubscription = activeSubscriptionsMap.get(subscribable.ApiName);
                currentEntry.mIsAuthorized = authMap.get(subscribable.Id);

                user.setSubscriptionCacheEntry(subscribable.ApiName, currentEntry);
            }
        }

        // Check and set access to fishingfacility data so we know this when loading the map later.
        user.setIsFishingFacilityAuthenticated(
                authMap.get(availableSubscriptionsMap.containsKey(getString(R.string.fishing_facility_api_name))
                        ? availableSubscriptionsMap.get(getString(R.string.fishing_facility_api_name)).Id
                        : -1));
        user.writeToSharedPref(getActivity());

        for (final PropertyDescription propertyDescription : availableSubscriptions) {
            boolean isAuthed = (authMap.get(propertyDescription.Id) != null
                    ? authMap.get(propertyDescription.Id)
                    : false);

            SubscriptionExpandableListChildObject currentPropertyDescriptionChildObject = setupAvailableSubscriptionChildView(
                    propertyDescription, activeSubscriptionsMap.get(propertyDescription.ApiName), isAuthed);

            availableSubscriptionObjectsList.add(currentPropertyDescriptionChildObject);
        }

        ExpandableListParentObject propertyDescriptionParent = new ExpandableListParentObject();

        propertyDescriptionParent.setChildObjectList(availableSubscriptionObjectsList);
        propertyDescriptionParent.setParentNumber(1);
        propertyDescriptionParent.setParentText(getString(R.string.my_page_all_available_subscriptions));
        propertyDescriptionParent.setResourcePathToImageResource(R.drawable.ikon_kart_til_din_kartplotter);

        parentObjectList.add(propertyDescriptionParent);

        childOnClickListener.setPropertyDescriptions(availableSubscriptions);
    } catch (Exception e) {
        Log.d(TAG, "Exception occured: " + e.toString());
    }

    return parentObjectList;
}

From source file:com.qsoft.components.gallery.utils.GalleryUtils.java

public static String orderImage(String url, List<ImageDTO> imageDTO, Long equipmentId) throws IOException {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    HttpClient httpclient = new DefaultHttpClient();
    ImageListDTO imageListDTO = new ImageListDTO(imageDTO);
    String strImageDto = new Gson().toJson(imageListDTO);
    HttpPost post = new HttpPost(url);
    //        HttpGet httpGet = new HttpGet(url + "?equipmentId=" + equipmentId + "&orderList=" + strImageDto);
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("equipmentId", equipmentId.toString()));
    pairs.add(new BasicNameValuePair("orderList", strImageDto));
    post.setEntity(new UrlEncodedFormEntity(pairs));
    String result = "";
    HttpResponse response = httpclient.execute(post);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        result = convertStreamToString(instream);
        instream.close();/*from  w  ww .  ja v  a  2  s . c  o  m*/
    }
    return result;
}

From source file:es.example.contacts.ui.ContactDetailFragment.java

/**
 * When the Fragment is first created, this callback is invoked. It initializes some key
 * class fields.// w  ww  . ja v a  2s  . c o  m
 */
@Override
public void onCreate(Bundle savedInstanceState) {

    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());

    super.onCreate(savedInstanceState);

    // Check if this fragment is part of a two pane set up or a single pane
    mIsTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);

    // Let this fragment contribute menu items
    setHasOptionsMenu(true);

    /*
     * The ImageLoader takes care of loading and resizing images asynchronously into the
     * ImageView. More thorough sample code demonstrating background image loading as well as
     * details on how it works can be found in the following Android Training class:
     * http://developer.android.com/training/displaying-bitmaps/
     */
    mImageLoader = new ImageLoader(getActivity(), getLargestScreenDimension()) {
        @Override
        protected Bitmap processBitmap(Object data) {
            // This gets called in a background thread and passed the data from
            // ImageLoader.loadImage().
            return loadContactPhoto((Uri) data, getImageSize());

        }
    };

    // Set a placeholder loading image for the image loader
    mImageLoader.setLoadingImage(R.drawable.ic_contact_picture_180_holo_light);

    // Tell the image loader to set the image directly when it's finished loading
    // rather than fading in
    mImageLoader.setImageFadeIn(false);
}