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.android.strictmodetest.StrictModeActivity.java

/** Called when the activity is first created. */
@Override/*from  w  w w  .  j  a  v a 2 s .  c o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    cr = getContentResolver();
    final SQLiteDatabase db = openOrCreateDatabase("foo.db", MODE_PRIVATE, null);

    final Button readButton = (Button) findViewById(R.id.read_button);
    readButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Cursor c = null;
            try {
                c = db.rawQuery("SELECT * FROM foo", null);
            } finally {
                if (c != null)
                    c.close();
            }
        }
    });

    final Button writeButton = (Button) findViewById(R.id.write_button);
    writeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
        }
    });

    final Button writeLoopButton = (Button) findViewById(R.id.write_loop_button);
    writeLoopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            long startTime = SystemClock.uptimeMillis();
            int iters = 1000;
            BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
            for (int i = 0; i < iters; ++i) {
                policy.onWriteToDisk();
            }
            long endTime = SystemClock.uptimeMillis();
            Log.d(TAG, "Time for " + iters + ": " + (endTime - startTime) + ", avg="
                    + (endTime - startTime) / (double) iters);
        }
    });

    final Button dnsButton = (Button) findViewById(R.id.dns_button);
    dnsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "Doing DNS lookup for www.l.google.com... " + "(may be cached by InetAddress)");
            try {
                InetAddress[] addrs = InetAddress.getAllByName("www.l.google.com");
                for (int i = 0; i < addrs.length; ++i) {
                    Log.d(TAG, "got: " + addrs[i]);
                }
            } catch (java.net.UnknownHostException e) {
                Log.d(TAG, "DNS error: " + e);
            }
        }
    });

    final Button httpButton = (Button) findViewById(R.id.http_button);
    httpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Note: not using AndroidHttpClient, as that comes with its
                // own pre-StrictMode network-on-Looper thread check.  The
                // intent of this test is that we test the network stack's
                // instrumentation for StrictMode instead.
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse res = httpClient.execute(new HttpGet("http://www.android.com/favicon.ico"));
                Log.d(TAG, "Fetched http response: " + res);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http2Button = (Button) findViewById(R.id.http2_button);
    http2Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Usually this ends up tripping in DNS resolution,
                // so see http3Button below, which connects directly to an IP
                InputStream is = new URL("http://www.android.com/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http3Button = (Button) findViewById(R.id.http3_button);
    http3Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // One of Google's web IPs, as of 2010-06-16....
                InputStream is = new URL("http://74.125.19.14/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button binderLocalButton = (Button) findViewById(R.id.binder_local_button);
    binderLocalButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mLocalServiceConn.stub.doDiskWrite(123 /* dummy */);
                Log.d(TAG, "local writeToDisk returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "local binderButton error: " + e);
            }
        }
    });

    final Button binderRemoteButton = (Button) findViewById(R.id.binder_remote_button);
    binderRemoteButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mRemoteServiceConn.stub.doDiskWrite(1);
                Log.d(TAG, "remote writeToDisk #1 returned: " + value);
                value = mRemoteServiceConn.stub.doDiskWrite(2);
                Log.d(TAG, "remote writeToDisk #2 returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderOneWayButton = (Button) findViewById(R.id.binder_oneway_button);
    binderOneWayButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                Log.d(TAG, "doing oneway disk write over Binder.");
                mRemoteServiceConn.stub.doDiskOneWay();
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderCheckButton = (Button) findViewById(R.id.binder_check_button);
    binderCheckButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int policy;
            try {
                policy = mLocalServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "local service policy: " + policy);
                policy = mRemoteServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "remote service policy: " + policy);
            } catch (RemoteException e) {
                Log.d(TAG, "binderCheckButton error: " + e);
            }
        }
    });

    final Button serviceDumpButton = (Button) findViewById(R.id.service_dump);
    serviceDumpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "About to do a service dump...");
            File file = new File("/sdcard/strictmode-service-dump.txt");
            FileOutputStream output = null;
            final StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
            try {
                StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
                output = new FileOutputStream(file);
                StrictMode.setThreadPolicy(oldPolicy);
                boolean dumped = Debug.dumpService("cpuinfo", output.getFD(), new String[0]);
                Log.d(TAG, "Dumped = " + dumped);
            } catch (IOException e) {
                Log.e(TAG, "Can't dump service", e);
            } finally {
                StrictMode.setThreadPolicy(oldPolicy);
            }
            Log.d(TAG, "Did service dump.");
        }
    });

    final Button lingerCloseButton = (Button) findViewById(R.id.linger_close_button);
    lingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(true);
        }
    });

    final Button nonlingerCloseButton = (Button) findViewById(R.id.nonlinger_close_button);
    nonlingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(false);
        }
    });

    final Button leakCursorButton = (Button) findViewById(R.id.leak_cursor_button);
    leakCursorButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            final StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
            try {
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                        .penaltyLog().penaltyDropBox().build());
                db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
                Cursor c = db.rawQuery("SELECT * FROM foo", null);
                c = null; // never close it
                Runtime.getRuntime().gc();
            } finally {
                StrictMode.setVmPolicy(oldPolicy);
            }

        }
    });

    final CheckBox checkNoWrite = (CheckBox) findViewById(R.id.policy_no_write);
    final CheckBox checkNoRead = (CheckBox) findViewById(R.id.policy_no_reads);
    final CheckBox checkNoNetwork = (CheckBox) findViewById(R.id.policy_no_network);
    final CheckBox checkPenaltyLog = (CheckBox) findViewById(R.id.policy_penalty_log);
    final CheckBox checkPenaltyDialog = (CheckBox) findViewById(R.id.policy_penalty_dialog);
    final CheckBox checkPenaltyDeath = (CheckBox) findViewById(R.id.policy_penalty_death);
    final CheckBox checkPenaltyDropBox = (CheckBox) findViewById(R.id.policy_penalty_dropbox);

    View.OnClickListener changePolicy = new View.OnClickListener() {
        public void onClick(View v) {
            StrictMode.ThreadPolicy.Builder newPolicy = new StrictMode.ThreadPolicy.Builder();
            if (checkNoWrite.isChecked())
                newPolicy.detectDiskWrites();
            if (checkNoRead.isChecked())
                newPolicy.detectDiskReads();
            if (checkNoNetwork.isChecked())
                newPolicy.detectNetwork();
            if (checkPenaltyLog.isChecked())
                newPolicy.penaltyLog();
            if (checkPenaltyDialog.isChecked())
                newPolicy.penaltyDialog();
            if (checkPenaltyDeath.isChecked())
                newPolicy.penaltyDeath();
            if (checkPenaltyDropBox.isChecked())
                newPolicy.penaltyDropBox();
            StrictMode.ThreadPolicy policy = newPolicy.build();
            Log.v(TAG, "Changing policy to: " + policy);
            StrictMode.setThreadPolicy(policy);
        }
    };
    checkNoWrite.setOnClickListener(changePolicy);
    checkNoRead.setOnClickListener(changePolicy);
    checkNoNetwork.setOnClickListener(changePolicy);
    checkPenaltyLog.setOnClickListener(changePolicy);
    checkPenaltyDialog.setOnClickListener(changePolicy);
    checkPenaltyDeath.setOnClickListener(changePolicy);
    checkPenaltyDropBox.setOnClickListener(changePolicy);
}

From source file:co.uk.socialticker.ticker.TickerActivity.java

private void onCreateTwitter() {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(TickerActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;//from   w  w  w  .  j a  v a  2 s.  c o  m
    }

    // 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(TickerActivity.this, "Twitter oAuth tokens",
                "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    // All UI elements
    btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
    btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
    btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
    txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
    lblUpdate = (TextView) findViewById(R.id.lblUpdate);

    llTwitter = (LinearLayout) findViewById(R.id.llTwitter);
    llCast = (LinearLayout) findViewById(R.id.llCast);

    /**
     * Twitter login button click event will call loginToTwitter() function
     * */
    btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call login twitter function
            loginToTwitter();
        }
    });

    /**
     * Button click event to Update Status, will call updateTwitterStatus()
     * function
     * */
    btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call update status function
            // Get the status from EditText
            String status = txtUpdate.getText().toString();

            // Check for blank text
            if (status.trim().length() > 0) {
                // update status
                new updateTwitterStatus().execute(status);
            } else {
                // EditText is empty
                Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    /**
     * Button click event for logout from twitter
     * */
    btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call logout twitter function
            logoutFromTwitter();
        }
    });

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

                // Hide login button
                btnLoginTwitter.setVisibility(View.GONE);

                // Show Update Twitter
                lblUpdate.setVisibility(View.VISIBLE);
                txtUpdate.setVisibility(View.VISIBLE);
                btnUpdateStatus.setVisibility(View.VISIBLE);
                btnLogoutTwitter.setVisibility(View.VISIBLE);

                // Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);

            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }
}

From source file:com.openerp.base.res.Res_PartnerSyncHelper.java

private void addContact(Context context, Account account, String partner_id, String name, String mail,
        String number, String mobile, String website, String street, String street2, String city, String zip,
        String company, String image) {

    ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
    int rawContactInsertIndex = operationList.size();

    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
    builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
    builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
    builder.withValue(RawContacts.SYNC1, partner_id);
    operationList.add(builder.build());/*from   w  ww . ja  v  a  2  s.  c o  m*/

    // Display Name
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
    builder.withValue(ContactsContract.Data.MIMETYPE,
            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
    builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
    operationList.add(builder.build());

    // Connection to send message from contact
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
    builder.withValue(ContactsContract.Data.MIMETYPE, "vnd.android.cursor.item/vnd.com.openerp.auth.profile");
    builder.withValue(ContactsContract.Data.DATA1, name);
    builder.withValue(ContactsContract.Data.DATA2, partner_id);
    builder.withValue(ContactsContract.Data.DATA3, "Send Message");
    operationList.add(builder.build());

    // Email
    if (!mail.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Email.DATA, mail);
        operationList.add(builder.build());
    }

    // Phone number
    if (!number.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number);
        operationList.add(builder.build());
    }

    // Mobile number
    if (!mobile.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobile);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        operationList.add(builder.build());
    }

    // Website
    if (!website.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Website.TYPE, website);
        operationList.add(builder.build());
    }

    // Address street 1
    if (!street.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, street);
        operationList.add(builder.build());
    }

    // Address street 2
    if (!street2.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, street2);
        operationList.add(builder.build());
    }

    // Address City
    if (!city.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, city);
        operationList.add(builder.build());
    }

    // Zip code
    if (!zip.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, zip);
        operationList.add(builder.build());
    }

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

    // Partner Image
    if (!image.equals("false")) {

        Bitmap bitmapOrg = Base64Helper.getBitmapImage(context, image);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, stream);

        operationList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray()).build());
    }

    // Organization
    if (!company.equals("false")) {
        operationList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
                .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
                        ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                .build());
    }

    try {
        mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.eurotong.orderhelperandroid.Common.java

@TargetApi(9)
public static void downloadFile(String fileName) {
    try {/*  ww  w .  j a  v  a  2  s  .co  m*/
        //http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        Date date = new Date();
        String datetime = dateFormat.format(date);
        // Create a URL for the desired page          
        URL url = new URL(
                Common.GetBaseUrl() + Customer.Current().CustomerID + "/" + fileName + "?d=" + datetime);

        // Read all the text returned by the server  

        BufferedInputStream in = new BufferedInputStream(url.openStream());

        //http://stackoverflow.com/questions/4228699/write-and-read-strings-to-from-internal-file
        FileOutputStream fos = MyApplication.getAppContext().openFileOutput(fileName, Context.MODE_PRIVATE);
        /*
        DataOutputStream out = 
            new DataOutputStream(fos);
                
        String str;
        while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
           Log.i(Define.APP_CATALOG, str);
           out.writeUTF(str);
        }
        */
        BufferedOutputStream out = new BufferedOutputStream(fos, 4096);
        byte[] data = new byte[4096];
        int bytesRead = 0, totalRead = 0;
        while ((bytesRead = in.read(data, 0, data.length)) >= 0) {
            out.write(data, 0, bytesRead);

            // update progress bar
            totalRead += bytesRead;
            /*
            int totalReadInKB = totalRead / 1024;
            msg = Message.obtain(parentActivity.activityHandler,
                            AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR,
                            totalReadInKB, 0);
            parentActivity.activityHandler.sendMessage(msg);
            */
        }

        in.close();
        //fos.close();
        out.close();

        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_file_finished),
                Toast.LENGTH_LONG).show();

        try {
            if (fileName.equals(Define.MENU_FILE_NAME)) {
                Product.ParseMenuList(Common.GetFileInputStreamFromStorage(fileName));
                Log.i(Define.APP_CATALOG, "menus size:" + "");
                Product.Reload();
            } else if (fileName.equals(Define.PRINT_LAYOUT_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_NAME);
                PrintLayout.Reload();
            } else if (fileName.equals(Define.BUSINESS_INFO_FILE_NAME)) {
                BusinessInfo bi = BusinessInfo
                        .Parse(Common.GetFileInputStreamFromStorage(Define.BUSINESS_INFO_FILE_NAME));
                Log.i(Define.APP_CATALOG, "setting: businessname:" + bi.getBusinessName());
                BusinessInfo.Reload();
            } else if (fileName.equals(Define.SETTING_FILE_NAME)) {
                Setting setting = Setting.Parse(Common.GetFileInputStreamFromStorage(Define.SETTING_FILE_NAME));
                Log.i(Define.APP_CATALOG, "setting: printer port" + setting.getPrinterPort());
                setting.Reload();
            } else if (fileName.equals(Define.PRINT_LAYOUT_BAR_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_BAR_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_BAR_NAME);
                PrintLayout.Reload();
            }

            else if (fileName.equals(Define.PRINT_LAYOUT_KITCHEN_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_KITCHEN_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_KITCHEN_NAME);
                PrintLayout.Reload();
            } else if (fileName.equals(Define.DEVICE_FILE)) {
                Device bi = Device.Parse(Common.GetFileInputStreamFromStorage(Define.DEVICE_FILE));
                Log.i(Define.APP_CATALOG, Define.DEVICE_FILE);
                Device.Reload();
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        Log.e(Define.APP_CATALOG, e.toString());
    } catch (IOException e) {
        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_error),
                Toast.LENGTH_LONG).show();
        Log.e(Define.APP_CATALOG, e.toString());
        e.printStackTrace();
    } catch (Exception e) {
        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_error),
                Toast.LENGTH_LONG).show();
        Log.e(Define.APP_CATALOG, e.toString());
    }
}

From source file:co.beem.project.beem.FacebookTextService.java

/**
 * {@inheritDoc}//from ww  w.j av  a 2s  . c om
 */
@Override
public void onCreate() {
    super.onCreate();
    smackAndroid = SmackAndroid.init(FacebookTextService.this);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    savingMessageQueue = new LinkedBlockingQueue<co.beem.project.beem.service.Message>();
    loadingUserAvatarQueue = new LinkedBlockingDeque<String>();
    stateChangeQueue = new LinkedBlockingQueue<User>();
    databaseHelper = getHelper();
    try {
        setupDatabaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
    }
    isRunning = true;
    sessionManager = new SessionManager(FacebookTextService.this);
    savingMessageOnBackgroundThread(new SavingNewMessageTask());
    savingMessageOnBackgroundThread(new UpdateUserStateTask());
    handler = new Handler();
    registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    registerReceiver(mOnOffReceiver, new IntentFilter(FacebookTextApplication.GET_AVATAR));
    registerReceiver(mOnOffReceiver, new IntentFilter(FacebookTextApplication.UPDATE_USER_STATE));
    registerReceiver(mOnOffReceiver,
            new IntentFilter(FacebookTextApplication.PUSH_NOTIFICATION_FAVORITE_ONLINE));
    mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    mSettings.registerOnSharedPreferenceChangeListener(mPreferenceListener);
    if (mSettings.getBoolean(FacebookTextApplication.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(FacebookTextApplication.ACCOUNT_USERNAME_KEY, "").trim();
    mLogin = StringUtils.parseName(tmpJid);
    boolean useSystemAccount = mSettings.getBoolean(FacebookTextApplication.USE_SYSTEM_ACCOUNT_KEY, false);
    mPort = DEFAULT_XMPP_PORT;
    mService = StringUtils.parseServer(tmpJid);
    mHost = mService;
    initMemorizingTrustManager();

    if (mSettings.getBoolean(FacebookTextApplication.ACCOUNT_SPECIFIC_SERVER_KEY, false)) {
        mHost = mSettings.getString(FacebookTextApplication.ACCOUNT_SPECIFIC_SERVER_HOST_KEY, "").trim();
        if ("".equals(mHost))
            mHost = mService;
        String tmpPort = mSettings.getString(FacebookTextApplication.ACCOUNT_SPECIFIC_SERVER_PORT_KEY, "5222");
        if (!"".equals(tmpPort))
            mPort = Integer.parseInt(tmpPort);
    }
    if (mSettings.getBoolean(FacebookTextApplication.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);
    savingMessageOnBackgroundThread(new DownloadAvatarTask());
    Log.d(TAG, "Create FacebookTextService \t id: " + mLogin + " \t host: " + mHost + "\tmPort" + mPort
            + "\t service" + mService);
}

From source file:com.ehelp.home.SuperAwesomeCardFragment.java

public void send_info() {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
            .detectNetwork().penaltyLog().build());
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
            .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
    String jsonStrng = "{" + "\"id\":" + user_id + ",\"type\":1," + "\"longitude\":" + lon + ","
            + "\"latitude\":" + lat + "}";
    String message = RequestHandler.sendPostRequest("http://120.24.208.130:1501/user/modify_information",
            jsonStrng);/* w ww  .j ava  2s.co  m*/
    if (message == "false") {
        Toast.makeText(getActivity().getApplicationContext(),
                "??", Toast.LENGTH_SHORT).show();
    } else {
        JSONObject jO = null;
        try {
            jO = new JSONObject(message);
            if (jO.getInt("status") == 500) {
                Toast.makeText(getActivity().getApplicationContext(), "fuck", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity().getApplicationContext(), "good job", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:kr.wdream.ui.DialogsActivity.java

@Override
public View createView(final Context context) {
    Log.d(LOG_TAG, "createView");

    sp = context.getSharedPreferences("connectMall", Context.MODE_PRIVATE);
    connect = sp.getBoolean("connecting", false);

    searchAdapter = new SearchAdapter(context, null, true, false, false, true);

    if (Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }// www .ja v a2 s.com

    searching = false;
    searchWas = false;

    this.context = context;

    AndroidUtilities.runOnUIThread(new Runnable() {
        @Override
        public void run() {
            Theme.loadRecources(context);
        }
    });

    //  ?
    //  ?  EditText?
    ActionBarMenu menu = actionBar.createMenu();
    if (!onlySelect && searchString == null) {
        passcodeItem = menu.addItem(1, kr.wdream.storyshop.R.drawable.lock_close);
        updatePasscodeButton();
    }
    final ActionBarMenuItem item = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_search)
            .setIsSearchField(true)
            .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
                @Override
                public void onSearchExpand() {
                    searching = true;
                    if (listView != null) {
                        if (searchString != null) {
                            listView.setEmptyView(searchEmptyView);
                            progressView.setVisibility(View.GONE);
                            emptyView.setVisibility(View.GONE);
                        }
                        if (!onlySelect) {
                            floatingButton.setVisibility(View.GONE);
                        }
                    }

                    if (clicktab1) {
                        tab1Searching = true;
                    }

                    updatePasscodeButton();
                }

                @Override
                public boolean canCollapseSearch() {
                    if (clicktab2) {
                        if (searchString != null) {
                            finishFragment();
                            return false;
                        }
                    }
                    return true;
                }

                @Override
                public void onSearchCollapse() {
                    if (clicktab2) {
                        searching = false;
                        searchWas = false;
                        if (listView != null) {
                            searchEmptyView.setVisibility(View.GONE);
                            if (MessagesController.getInstance().loadingDialogs
                                    && MessagesController.getInstance().dialogs.isEmpty()) {
                                emptyView.setVisibility(View.GONE);
                                listView.setEmptyView(progressView);
                            } else {
                                progressView.setVisibility(View.GONE);
                                listView.setEmptyView(emptyView);
                            }
                            if (!onlySelect) {
                                floatingButton.setVisibility(View.VISIBLE);
                                floatingHidden = true;
                                floatingButton.setTranslationY(AndroidUtilities.dp(100));
                                hideFloatingButton(false);
                            }
                            if (listView.getAdapter() != dialogsAdapter) {
                                listView.setAdapter(dialogsAdapter);
                                dialogsAdapter.notifyDataSetChanged();
                            }
                        }
                        if (dialogsSearchAdapter != null) {
                            dialogsSearchAdapter.searchDialogs(null);
                        }
                    }
                    if (clicktab1) {
                        searchAdapter.searchDialogs(null);
                        searching = false;
                        searchWas = false;
                        listContacts.setAdapter(LaunchActivity.contactsAdapter);
                        LaunchActivity.contactsAdapter.notifyDataSetChanged();
                        listContacts.setFastScrollAlwaysVisible(true);
                        listContacts.setFastScrollEnabled(true);
                        listContacts.setVerticalScrollBarEnabled(false);
                    }
                    updatePasscodeButton();
                }

                @Override
                public void onTextChanged(EditText editText) {
                    String text = editText.getText().toString();
                    if (clicktab2) {
                        if (text.length() != 0
                                || dialogsSearchAdapter != null && dialogsSearchAdapter.hasRecentRearch()) {
                            contentLayout.setVisibility(View.GONE);
                            listContacts.setVisibility(View.GONE);
                            lytDialogs.setVisibility(View.VISIBLE);
                            searchWas = true;
                            if (dialogsSearchAdapter != null && listView.getAdapter() != dialogsSearchAdapter) {
                                listView.setAdapter(dialogsSearchAdapter);
                                dialogsSearchAdapter.notifyDataSetChanged();
                            }
                            if (searchEmptyView != null && listView.getEmptyView() != searchEmptyView) {
                                emptyView.setVisibility(View.GONE);
                                progressView.setVisibility(View.GONE);
                                searchEmptyView.showTextView();
                                listView.setEmptyView(searchEmptyView);
                            }
                        }
                        if (dialogsSearchAdapter != null) {
                            dialogsSearchAdapter.searchDialogs(text);
                        }
                    }
                    if (clicktab1) {
                        if (LaunchActivity.contactsAdapter == null) {
                            return;
                        }
                        if (text.length() != 0) {
                            searchWas = true;
                            if (listView != null) {
                                listContacts.setAdapter(searchAdapter);
                                searchAdapter.notifyDataSetChanged();
                                listContacts.setFastScrollAlwaysVisible(false);
                                listContacts.setFastScrollEnabled(false);
                                listContacts.setVerticalScrollBarEnabled(true);
                            }
                        }
                        searchAdapter.searchDialogs(text);
                    }
                }
            });
    item.getSearchField().setHint(LocaleController.getString("Search", kr.wdream.storyshop.R.string.Search));
    if (onlySelect) {
        actionBar.setBackButtonImage(kr.wdream.storyshop.R.drawable.ic_ab_back);
        actionBar.setTitle(LocaleController.getString("SelectChat", kr.wdream.storyshop.R.string.SelectChat));
    } else {
        if (searchString != null) {
            actionBar.setBackButtonImage(kr.wdream.storyshop.R.drawable.ic_ab_back);
        } else {
            actionBar.setBackButtonDrawable(new MenuDrawable());
        }
        if (BuildVars.DEBUG_VERSION) {
            actionBar.setTitle(
                    LocaleController.getString("AppNameBeta", kr.wdream.storyshop.R.string.AppNameBeta));
        } else {
            actionBar.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
        }
    }
    actionBar.setAllowOverlayTitle(true);

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            Log.d(LOG_TAG, "DialogsActivity ItemClick");
            if (id == -1) {
                if (onlySelect) {
                    finishFragment();
                    Log.d(LOG_TAG, "onySelect finishFragment");
                } else if (parentLayout != null) {
                    parentLayout.getDrawerLayoutContainer().openDrawer(false);
                    Log.d(LOG_TAG, "parentLayout.getDrawerLayoutContainer().openDrawer(false);");
                }
            } else if (id == 1) {
                UserConfig.appLocked = !UserConfig.appLocked;
                UserConfig.saveConfig(false);
                updatePasscodeButton();
                Log.d(LOG_TAG, "updatePasscodeButton");
            }
        }
    });

    initView();

    return fragmentView;
}

From source file:com.team08storyapp.ESHelper.java

/**
 * Returns a list of stories from the webservice that contain the searched
 * text in either their Author or Title fields.
 * <p>/*from www. j  av a 2s  .  c  o  m*/
 * The method uses ElisticSearch (@link http://www.elasticsearch.org/guide/)
 * to retrieve the story from the webservice.
 * 
 * @param searchString
 *            A text string containing the key set of words to use in
 *            searching the webservices Stories.
 * @return A list of stories that contain the text used in the search in
 *         either their Author or Title fields.
 */
public ArrayList<Story> searchOnlineStories(String searchString) {
    searchString = searchString.toLowerCase(Locale.US);

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

    ArrayList<Story> stories = new ArrayList<Story>();

    if (!searchString.matches(".*\\w.*") || searchString.contains("\n")) {
        return getOnlineStories();
    }

    try {
        /*
         * Create a HttpPost object to retrieve the Stories from the
         * webservice
         */
        HttpPost searchRequest = new HttpPost(
                "http://cmput301.softwareprocess.es:8080/cmput301f13t08/_search?pretty=1");

        /*
         * Create the ElasticSearch query string to search the webservice
         * for the search text
         */
        String query = "{\"fields\": [\"onlineStoryId\",\"title\",\"author\"], \"query\": {\"query_string\" :{ \"fields\":[\"title\",\"author\"], \"query\":\""
                + searchString + "\"}}}";
        StringEntity stringentity = new StringEntity(query);

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

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

        /* 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);
        Log.d(TAG, esResponse.toString());
        /* We get the story from it! */
        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;
}