在Android上从图库上传图片时手机被绞死了

时间:2015-02-07 04:07:09

标签: java android

我想从图库上传图片,使其成为我的个人资料图片。但我的手机被绞死了几秒钟,之后,它进入正常模式并上传图片有一些延迟。任何人都可以帮我避免挂起并快速上传图片。

这是我的代码。

public void res() {


        System.out.println("res method for jscript");
        webView.loadUrl("javascript:callFromActivity(\"" + msgToSend + "\")");
    }

    public void showCustomAlert() {
        // TODO Auto-generated method stub

        Context context = getApplicationContext();
        // Create layout inflator object to inflate toast.xml file
        LayoutInflater inflater = getLayoutInflater();

        // Call toast.xml file for toast layout
        View toastRoot = inflater.inflate(R.layout.toast, null);

        Toast toast = new Toast(context);

        // Set layout to toast
        toast.setView(toastRoot);
        toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
                0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.show();

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    if(data!=null)
    {
        if (requestCode == CAM_REQUREST) {
             Bundle extras = data.getExtras();

             if (extras != null) {
            bitmap_profile_image = extras.getParcelable("data");            
            bitmap_profile_image = (Bitmap) data.getExtras().get("data");
            imagepath = ImageWrite(bitmap_profile_image);
        }
        }

        else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            imagepath = ImageWrite(BitmapFactory.decodeFile(picturePath));

        } else {

        }
    }

            Imageuploading();

    }

    public String ImageWrite(Bitmap bitmap1) {

        String extStorageDirectory = Environment.getExternalStorageDirectory()
                .toString();
        OutputStream outStream = null;
        File file = new File(extStorageDirectory, "selectimage.PNG");

        try {

            outStream = new FileOutputStream(file);
            bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outStream);`enter code here`
            outStream.flush();
            outStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
        String imageInSD = "/sdcard/selectimage.PNG";

        return imageInSD;

    }

    protected void Imageuploading() {
        // TODO Auto-generated method stub

        try {

            Log.e("imageuploading", "dfdf");

            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
            DataInputStream inputStream = null;

            String pathToOurFile = (String) imagepath;

            // String urlServer =
            // "http://demo.cogzideltemplates.com/client/snapchat-clone/index.php/user/image_upload";
            String urlServer = Liveurl+"mobile/image_upload";
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;

            FileInputStream fileInputStream = new FileInputStream(new File(
                    pathToOurFile));

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream
                    .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                            + pathToOurFile + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            // Toast.makeText(getApplicationContext(), serverResponseMessage,
            // Toast.LENGTH_LONG).show();
            System.out.println("image" + serverResponseMessage);

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

            DataInputStream inputStream1 = null;
            inputStream1 = new DataInputStream(connection.getInputStream());
            String str = "";
            String Str1_imageurl = "";

            while ((str = inputStream1.readLine()) != null) {
                Log.e("Debug", "Server Response " + str);

                Str1_imageurl = str;
                Log.e("Debug", "Server Response String imageurl" + str);
            }
            inputStream1.close();
            System.out.println("image url inputstream1 " + Str1_imageurl);
            // Toast.makeText(getApplicationContext(), Str1_imageurl,
            // Toast.LENGTH_LONG).show();

            msgToSend = Str1_imageurl.trim();

            System.out.println("message to send "+msgToSend);

        } catch (Exception e) {

            e.printStackTrace();

        }

        res();

    }

    public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());

        System.out.println("application dir"+appDir);
        if (appDir.exists()) {
            String[] children = appDir.list();
            for (String s : children) {
                if (!s.equals("lib")) {
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
                    Intent i=new Intent(Profile_settings.this,splash.class);
                    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                   // clearApplicationData();
                    startActivity(i);
                }
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }
    private void loadSavedPreferences() {    
        //User has successfully logged in, save this information
        // We need an Editor object to make preference changes.

        SharedPreferences settings = getSharedPreferences(index.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();`enter code here`
        editor.commit();

        }

提前致谢。

0 个答案:

没有答案