如何修复文件存储路径

时间:2017-08-01 03:28:23

标签: android android-intent email-attachments

所以我在这里尝试做的是收集用户的信息,然后收集他/她的签名,然后将其附加到电子邮件中。

String pilot, ship, to, from, zone1, zone2, CallSign, agent, date, imgPath;
Toolbar toolbar;
Button btn_get_sign, mClear, mGetSign, mCancel, btn_send;
double vesselUnit;
Dialog dialog;
File file;
LinearLayout mContent;
View view;
signature mSignature;
Bitmap bitmap;


File fileDIRECTORY = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)  + "/extSdCard" + "/DigitalSign");
String DIRECTORY= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/extSdCard" + "/DigitalSign";
String rootpic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String pic_name = rootpic_name + ".JPEG";
String StoredPath = DIRECTORY + File.separator + rootpic_name + ".JPEG";




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_digital_signature);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        pilot = extras.getString("Pilot");
        ship = extras.getString("ship");
        to = extras.getString("to");
        from = extras.getString("from");
        zone1 = extras.getString("zone1");
        zone2 = extras.getString("zone2");
        CallSign = extras.getString("callsign");
        agent = extras.getString("agent");
        vesselUnit = extras.getDouble("vesselunits");
        date = extras.getString("date");
    }
    // Setting ToolBar as ActionBar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Button to open signature panel
    btn_get_sign = (Button) findViewById(R.id.signature);
    btn_send= (Button) findViewById(R.id.btn_send);
    // Method to create Directory, if the Directory doesn't exists

    dialog = new Dialog(this);
    // Removing the features of Normal Dialogs
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_sig);
    dialog.setCancelable(true);

    btn_get_sign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Function call for Digital Signature
            dialog_action();

        }
    });
    btn_send.setOnClickListener(new OnClickListener() {
        public void onClick(View v){

            Uri upath = Uri.parse("file://" + StoredPath);
            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            emailIntent.putExtra(Intent.EXTRA_TEXT, "Pilot: "+pilot+"\nShip: "+ship+"\n"+"Destination: "+to+"\n"+"Departure location: "+from+"\n"+"Zone 1: "+zone1+"\n"+"Zone 2: "+zone2+"\n"+"Callsign: "+CallSign+"\n"+"Angent: "+agent+"\n"+"Vessel Units: "+vesselUnit);
            // set the type to 'email'
            emailIntent.setType("image/*");
            String to[] = {"myemail@gmail.com"};
            emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
            // the attachment
            emailIntent.putExtra(Intent.EXTRA_STREAM, upath);
            Log.d("TAG","Tagged");
            // the mail subject
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, pilot+"'s Ticket for "+ship);


            startActivity(Intent.createChooser(emailIntent , "Send email..."));
        }
    });
}

// Function for Digital Signature
public void dialog_action() {

    mContent = (LinearLayout) dialog.findViewById(R.id.linearLayout);
    mSignature = new signature(getApplicationContext(), null);
    mSignature.setBackgroundColor(Color.WHITE);
    // Dynamically generating Layout through java code
    mContent.addView(mSignature, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    mClear = (Button) dialog.findViewById(R.id.clear);
    mGetSign = (Button) dialog.findViewById(R.id.getsign);
    mGetSign.setEnabled(false);
    mCancel = (Button) dialog.findViewById(R.id.cancel);
    view = mContent;

    mClear.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v("tag", "Panel Cleared");
            mSignature.clear();
            mGetSign.setEnabled(false);
        }
    });
    mGetSign.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            Log.v("tag", "Panel Saved");
            view.setDrawingCacheEnabled(true);
            if(isExternalStorageReadable() && isExternalStorageWritable()) {
                file=mSignature.save(view);
                dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
                // Calling the same class
                recreate();
            }
            else{Toast.makeText(getApplicationContext(), "NOT Saved", Toast.LENGTH_SHORT).show();}
        }
    });
    mCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v("tag", "Panel Cancelled");
            dialog.dismiss();
            // Calling the same class
            recreate();
        }
    });
    dialog.show();
}


public class signature extends View {
    private static final float STROKE_WIDTH = 5f;
    private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
    private Paint paint = new Paint();
    private Path path = new Path();

    private float lastTouchX;
    private float lastTouchY;
    private final RectF dirtyRect = new RectF();

    public signature(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(STROKE_WIDTH);
    }

    public File save(View v) {
        Log.v("tag", "Width: " + v.getWidth());
        Log.v("tag", "Height: " + v.getHeight());
        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
        }
        Canvas canvas = new Canvas(bitmap);
        fileDIRECTORY.mkdirs();
        File nfile = new File (fileDIRECTORY,pic_name);
        try {
            // Output the file
            FileOutputStream mFileOutStream  = new FileOutputStream(nfile);
            v.draw(canvas);
            // Convert the output file to Image such as .png
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, mFileOutStream);
            mFileOutStream.flush();
            mFileOutStream.close();
            MediaScannerConnection.scanFile(getApplicationContext(), new String[] { nfile.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });


        } catch (Exception e) {
            e.printStackTrace();
        }
        return nfile;
    }

    public void clear() {
        path.reset();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();
        mGetSign.setEnabled(true);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(eventX, eventY);
                lastTouchX = eventX;
                lastTouchY = eventY;
                return true;

            case MotionEvent.ACTION_MOVE:

            case MotionEvent.ACTION_UP:
                resetDirtyRect(eventX, eventY);
                int historySize = event.getHistorySize();
                for (int i = 0; i < historySize; i++) {
                    float historicalX = event.getHistoricalX(i);
                    float historicalY = event.getHistoricalY(i);
                    expandDirtyRect(historicalX, historicalY);
                    path.lineTo(historicalX, historicalY);
                }
                path.lineTo(eventX, eventY);
                break;
            default:
                debug("Ignored touch event: " + event.toString());
                return false;
        }

        invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

        lastTouchX = eventX;
        lastTouchY = eventY;

        return true;
    }

    private void debug(String string) {
        Log.v("log_tag", string);
    }

    private void expandDirtyRect(float historicalX, float historicalY) {
        if (historicalX < dirtyRect.left) {
            dirtyRect.left = historicalX;
        } else if (historicalX > dirtyRect.right) {
            dirtyRect.right = historicalX;
        }

        if (historicalY < dirtyRect.top) {
            dirtyRect.top = historicalY;
        } else if (historicalY > dirtyRect.bottom) {
            dirtyRect.bottom = historicalY;
        }
    }

    private void resetDirtyRect(float eventX, float eventY) {
        dirtyRect.left = Math.min(lastTouchX, eventX);
        dirtyRect.right = Math.max(lastTouchX, eventX);
        dirtyRect.top = Math.min(lastTouchY, eventY);
        dirtyRect.bottom = Math.max(lastTouchY, eventY);
    }
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state))
    {
        Log.d("TRACE","ISWRITEABLE");
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
    {
        Log.d("TRACE","ISREADABLE");
        return true;
    }
    return false;
}
public static void addImageToGallery(final String filePath, final Context context) {

    ContentValues values = new ContentValues();

    values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.MediaColumns.DATA, filePath);
    try{
        context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
    }catch(Exception e){
        Log.d("TAG","Not Saved in gallery");
    }

}

}

所以我创建了目录,但图片没有附加,也没有显示在文件目录中。我没有看到我的问题出现在哪里,但我肯定知道图片未被处理或未在文件中正确保存。

2 个答案:

答案 0 :(得分:1)

我建议你先了解android存储模型 当我们在android中讨论内部和外部存储时,有很多困惑。 这主要是因为。

  

我们想到什么:

我们对外部存储的理解是SD卡,这是不对的。

  

Android SDK认为:

每个Android兼容设备都支持共享&#34;外部存储&#34;您可以用来保存文件。这可以是可移动存储介质(例如SD卡)或内部(不可移动)存储。保存到外部存储器的文件是世界可读的,当用户启用USB海量存储器在计算机上传输文件时,可以对其进行修改。

这是一个很好的资源来阅读更多内容 Internal StorageExternal Storage

编辑:当您为多个制造商开发应用时,尽量不要硬编码路径,因为它因制造商而异。

答案 1 :(得分:0)

将您的路径目录更改为

File DIRECTORY = new File(Environment.getExternalStorageDirectory()
                    .getParent() + "/extSdCard" + "/DigitalSign");

记录

  

/存储/模拟/ extSdCard / DigitalSign