Access Internal Storage 存取android手機內存


Android 手機的內存是放在 /data/data/<package name>/files,可以使用getFilesDir()得到路徑。如下:

File fileDir = getFilesDir();

每一個app有各自的user id和自己權限跟空間。所以存在手機內存的資料就會權限的問題。要開啟或創建時就需要權限的設定。以android developer內的說法,存取內存要使用openFileOutput這個程式,反回為FileOutputStream。如下:

FileOutputStream imageFout = openFileOutput("FileName",MODE_WORLD_READABLE);

FileName只要檔名即可,不用完整路徑。

Context.MODE_PRIVATE:代表該檔是私有資料,只能被APP本身訪問。如果檔案已存在,會覆蓋原檔。

Context.MODE_APPEND:會檢查檔案是否存在,存在則將內容增加到檔案內;如檔案不存在就創建新檔。

Context.MODE_WORLD_READABLE:其它應用程式也可以讀。如果要在APP中使用 intent.ACTION_SEND,要使用此模式。

Context.MODE_WORLD_WRITEABLE:其它應用程式也可以寫入此檔。


如想要兩個模式共有,如下

openFileOutput("FileName", MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE);


Developer 中的範例如下(建立文字檔)


String FILENAME = "hello_file";
String string = "hello world!";
try{
     FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
     fos.write(string.getBytes());
     fos.close();
}catch(IOException e){
    Log.e("panel","IOEception",e);
}

 

 另一範例將Bitmap存入,如下


try{
FileOutputStream imageFout = mc.openFileOutput(imageFile.getName(),Context.MODE_WORLD_READABLE);
bm.compress(Bitmap.CompressFormat.JPEG,100,imageFout);
    imageFout.close();
}catch(IOException e){
    Log.e("panel","IOEception",e);
}

一個完整的分享圖片範例


File fileDir = mc.getFilesDir();
String imagePath=fileDir+java.io.File.separator+"test.jpg";
        

File imageFile=new File(imagePath);
        

try{
            FileOutputStream imageFout = mc.openFileOutput(imageFile.getName(),Context.MODE_WORLD_READABLE);
            bm.compress(Bitmap.CompressFormat.JPEG,100,imageFout);
            imageFout.close();
        }catch(IOException e){
            Log.e("panel","IOEception",e);
        }
   
        Uri imageUri=Uri.fromFile(imageFile);
        Intent shareIntent=new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "主題");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "說明");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        mc.startActivity(Intent.createChooser(shareIntent, "分享…"));
      





留言

這個網誌中的熱門文章

python 找圖自動點擊

Python pyserial 抓取系統內的 COM PORT

VBA EXCEL 工作表變化 馬上執行 的作法 Worksheet_Change