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:com.yattatech.dbtc.activity.SplashScreen.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (FACADE.isDeviceClockOutOfSync()) {
        Debug.d(mTag, "System clock is not supported");
        showMessage(R.string.system_clock_outof_sync);
        finish();/*from w w  w.  j  a v  a 2  s. c  o m*/
        return;
    }
    setContentView(R.layout.layout_splash_screen);
    mView = findViewById(R.id.content);
    mAnim = AnimationUtils.loadAnimation(this, R.anim.activity_open_scale);
    mView.setAnimation(mAnim);
    mAnim.setAnimationListener(mViewAnimationListener);
    Crittercism.initialize(getApplicationContext(), getString(R.string.crittercism_id));
    // make sure set android:debuggable as false, avoiding 
    // execution of bellow code block in release version
    final ApplicationInfo info = getApplicationInfo();
    if ((info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
        Debug.d(mTag, "defining thread policy");
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
                .detectNetwork().penaltyLog().build());
        Debug.d(mTag, "defining VM policy");
        StrictMode.setVmPolicy(
                new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog().build());
    }
    if (Debug.isDebugable()) {
        // Usefull to know current database state using some
        // external sqlite tool to check it out, for copying
        // that file to computer use adb command line
        DbUtil.copyDatabase(Environment.getExternalStorageDirectory().getAbsolutePath());
    }
}

From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java

/**
 * Returns the instance of ServerClient, or generates it if has not yet be instantiated.
 * @return The instance of the ServerClient
 *//*from w ww. ja va  2 s .c om*/
public static ServerClient getInstance() {
    if (instance == null) {
        /* Allow networking on main thread. Will be changed later so networking tasks are asynchronous. */
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        instance = new ServerClient();
        dbManager = ResultsDbManager.getInstance();
        httpclient = ServerClient.getThreadSafeClient();
        helper = new ClientHelper();
    }
    return instance;
}

From source file:com.glasshack.checkmymath.CheckMyMath.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    showBlankCard();//from  w  w w  .ja  v  a2  s .  co  m

    // Added this to connect to web service 
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
}

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

@TargetApi(VERSION_CODES.HONEYCOMB)
public static void enableStrictMode() {
    if (GalleryUtils.hasGingerbread()) {
        StrictMode.ThreadPolicy.Builder threadPolicyBuilder = new StrictMode.ThreadPolicy.Builder().detectAll()
                .penaltyLog();//from   w w  w  .  ja v  a  2s .c o  m
        StrictMode.VmPolicy.Builder vmPolicyBuilder = new StrictMode.VmPolicy.Builder().detectAll()
                .penaltyLog();

        if (GalleryUtils.hasHoneycomb()) {
            threadPolicyBuilder.penaltyFlashScreen();
            vmPolicyBuilder.setClassInstanceLimit(DISUploadImageActivity_.class, 1);
            //                        .setClassInstanceLimit(DISUploadImageActivity_.class, 1);
        }
        StrictMode.setThreadPolicy(threadPolicyBuilder.build());
        StrictMode.setVmPolicy(vmPolicyBuilder.build());
    }
}

From source file:com.brodev.socialapp.view.BlogDetail.java

/** Called when the activity is first created. */
@Override//from   w w w.  j  av a2 s. c  om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blog_content_view);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    Bundle bundle = getIntent().getExtras();
    blog = (Blog) bundle.get("blog");

    user = (User) getApplicationContext();
    colorView = new ColorView(getApplicationContext());
    this.imageGetter = new ImageGetter(getApplicationContext());

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

    if (blog.getTime_stamp().equals("0")) {
        this.getBlogAdapter();
    }

    initView();
    // get comment fragment
    Bundle comment = new Bundle();
    comment.putString("type", "blog");
    comment.putInt("itemId", blog.getBlog_id());
    comment.putInt("totalComment", blog.getTotal_comment());
    comment.putInt("total_like", blog.getTotal_like());
    comment.putBoolean("no_share", blog.getShare());
    comment.putBoolean("is_liked", blog.getIs_like());
    comment.putBoolean("can_post_comment", blog.isCanPostComment());

    CommentFragment commentFragment = new CommentFragment();
    commentFragment.setArguments(comment);
    getSupportFragmentManager().beginTransaction().add(R.id.commentfragment_wrap, commentFragment).commit();
}

From source file:cz.cvut.via.androidrestskeleton.SkeletonActivity.java

/** Called with the activity is first created. */
@Override//w w w  .  j  a va 2 s .  c  o m
public void onCreate(Bundle savedInstanceState) {

    // DISABLE policy not allowing network connections from main application thread
    // these calls normally HAVE to be done from worker threads/asynchronous threads/services ..
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    super.onCreate(savedInstanceState);

    // Inflate our UI from its XML layout description.
    setContentView(R.layout.skeleton_activity);

    requestView = (CheckedTextView) findViewById(R.id.checkedTextRequest);
    responseView = (CheckedTextView) findViewById(R.id.checkedTextResponse);

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.create)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            PostalAddress address = new PostalAddress();
            address.setCity("new city");
            address.setCountry("new country");
            address.setStreet("new street");
            address.setZipCode("zipcode");

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/";

            new AsyncPOST<PostalAddress>(requestEntity) {
                protected void onPostExecute(Response<String> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n"
                            + request.getBody().toJSONString());
                    responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                            + result.getResponseEntity().getHeaders().toString());
                    lastCreatedLocation = result.getResponseEntity().getHeaders().getLocation().getPath();
                };
            }.execute(url);
        }
    });

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.list)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            RestTemplate restTemplate = new RestTemplate();

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/";

            new AsyncGET<PostalAddress[]>(requestEntity, PostalAddress[].class) {
                protected void onPostExecute(Response<PostalAddress[]> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        StringBuilder text = new StringBuilder();
                        for (PostalAddress address : result.getResponseEntity().getBody()) {
                            text.append(address.toJSONString() + "\n\n");
                        }
                        //+ requestEntity.getBody().toJSONString());
                        responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                                + result.getResponseEntity().getHeaders().toString() + "\n\n" + text);
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.update)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            PostalAddress address = new PostalAddress();
            address.setCity("updated city");
            address.setCountry("new country");
            address.setStreet("new street");
            address.setZipCode("zipcode");

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation;

            new AsyncPUT<PostalAddress>(requestEntity) {
                protected void onPostExecute(Response<Object> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n"
                            + request.getBody().toJSONString());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        responseView.setText("PUT method in Spring does not support return values..");
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.delete)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation;

            // get reponse
            new AsyncDELETE() {
                protected void onPostExecute(Response<Object> result) {
                    requestView.setText(url);

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        responseView.setText("PUT method in Spring does not support return values..");
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.query)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            HashMap<String, String> query = new HashMap<String, String>();
            query.put("setFilter", "street == streetParam");
            query.put("declareParameters", "String streetParam");
            query.put("setOrdering", "street desc");

            HashMap<String, String> parameters = new HashMap<String, String>();
            parameters.put("streetParam", "new street");

            RESTQuery q = new RESTQuery();
            q.setQuery(query);
            q.setParameters(parameters);

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<RESTQuery> requestEntity = new HttpEntity<RESTQuery>(q, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/q";

            // get reponse
            new AsyncPOST_QUERY<RESTQuery, PostalAddress[]>(requestEntity, PostalAddress[].class) {
                @Override
                protected void onPostExecute(Response<PostalAddress[]> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {

                        StringBuilder text = new StringBuilder();
                        for (PostalAddress address : result.getResponseEntity().getBody()) {
                            text.append(address.toJSONString() + "\n\n");
                        }

                        responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                                + result.getResponseEntity().getHeaders().toString() + "\n\n" + text);
                    }
                }
            }.execute(url);
        }
    });

}

From source file:com.andrew.apollo.ApolloApplication.java

@TargetApi(11)
private void enableStrictMode() {
    if (ApolloUtils.hasGingerbread() && BuildConfig.DEBUG) {
        final StrictMode.ThreadPolicy.Builder threadPolicyBuilder = new StrictMode.ThreadPolicy.Builder()
                .detectAll().penaltyLog();
        final StrictMode.VmPolicy.Builder vmPolicyBuilder = new StrictMode.VmPolicy.Builder().detectAll()
                .penaltyLog();//from   ww  w  .  ja va2 s .  c  o  m

        if (ApolloUtils.hasHoneycomb()) {
            threadPolicyBuilder.penaltyFlashScreen();
        }
        StrictMode.setThreadPolicy(threadPolicyBuilder.build());
        StrictMode.setVmPolicy(vmPolicyBuilder.build());
    }
}

From source file:by.onliner.news.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from   w  w  w.  java2  s.  c o  m*/

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

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    mDrawerLayout.addDrawerListener(toggle);
    mDrawerLayout.addDrawerListener(this);
    toggle.syncState();

    mNavigationView = (NavigationView) findViewById(R.id.nav_view);
    mNavigationView.setNavigationItemSelectedListener(this);

    View headerNavigationView = mNavigationView.getHeaderView(0);

    mButtonAuth = (Button) headerNavigationView.findViewById(R.id.bt_auth_account);
    mButtonAuth.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mDrawerLayout.closeDrawer(Gravity.LEFT);
            Intent intent = new Intent(App.getContext(), AuthActivity.class);
            startActivity(intent);
        }
    });

    mButtonLogout = (Button) headerNavigationView.findViewById(R.id.bt_logout_account);
    mButtonLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mDrawerLayout.closeDrawer(Gravity.LEFT);
            App.logoutUser();
            updateNavBarLoginInfo();
        }
    });

    mImageViewNavBarAvatar = (ImageView) headerNavigationView.findViewById(R.id.img_nav_header_avatar);
    mTextViewNavBarUsername = (TextView) headerNavigationView.findViewById(R.id.tv_nav_bar_username);

    updateNavBarLoginInfo();

    mTitles = new CharSequence[] { getString(R.string.tabAuto), getString(R.string.tabPeoples),
            getString(R.string.tabRealt), getString(R.string.tabTechnologies) };

    mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mTitles, Numboftabs);

    mPager = (ViewPager) findViewById(R.id.pager_news_list);
    mPager.setOffscreenPageLimit(1);
    mPager.setAdapter(mAdapter);

    mTabs = (TabLayout) findViewById(R.id.tabs_news_list);
    mTabs.setupWithViewPager(mPager);
}

From source file:net.giovannicapuano.galax.util.Utils.java

/**
 * Perform a HTTP GET request.//from w  ww .j  ava2 s  .  co m
 */
public static HttpData get(String path, Context context) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);

    int status = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    String body = "";

    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, new PersistentCookieStore(context));
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());

    try {
        HttpGet httpGet = new HttpGet(context.getString(R.string.server) + path);
        HttpResponse response = httpClient.execute(httpGet, localContext);

        status = response.getStatusLine().getStatusCode();
        body = EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new HttpData(status, body);
}

From source file:com.streamdataio.android.stockmarket.StockMarketList.java

/**
 * Android application creation callback.
 *
 * @param savedInstanceState contains environment variables & values
 *///from w  ww  .j  a v a 2  s .co  m
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    System.out.println("onCreate() callback");

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

    // Set the Activity layout
    setContentView(R.layout.main);

    try {
        data = mapper.readTree("[]");
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Configure the list view
    listView = (ListView) findViewById(R.id.listView);
    listAdapter = new MyListAdapter(this, (ArrayNode) data);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    listView.setAdapter(listAdapter);
}