1. 程式人生 > >Android之內建和外接sdcard路徑顯示並且寫入資料

Android之內建和外接sdcard路徑顯示並且寫入資料

1、效果圖片

2、部分程式碼

package com.example.sdcardcheck;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	public static String TAG = "SdCardCheck";
	public TextView mTv;
	public Button mBtIn;
	public Button mBtout;
	public String result = "";
	public String inSdcardPath = "";
	public String outSdcaraPath = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mTv = (TextView)findViewById(R.id.text);
		mBtIn = (Button)findViewById(R.id.button_in);
		mBtout = (Button)findViewById(R.id.button_out);
//		checkPerssiom();
		mBtIn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// 獲取SD卡的目錄
				saveDataToSdcard(inSdcardPath, "inSdcard_text.txt");
			}
		});
		mBtout.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				saveDataToSdcard(outSdcaraPath, "outSdcard_text.txt");
			}
		});
		checkSd();
		getCommonPath();
		getStoragePath(this, true);
		getStoragePath(this, false);
		getExternalStoreAvailableSize();
		mTv.setText(result);
	}
	
	public void checkSd() {
		String state = Environment.getExternalStorageState();
		result += "Environment.MEDIA_MOUNTED is:" + state.equals(Environment.MEDIA_MOUNTED) + "\n";
		result += "Environment.MEDIA_MOUNTED_READ_ONLY is:" + state.equals(Environment.MEDIA_MOUNTED_READ_ONLY) + "\n";
		result += "Environment.MEDIA_SHARED is:" + state.equals(Environment.MEDIA_SHARED) + "\n";
		
		Log.d(TAG, "state.equals(Environment.MEDIA_MOUNTED is:" + state.equals(Environment.MEDIA_MOUNTED));
		Log.d(TAG, "state.equals(Environment.MEDIA_MOUNTED_READ_ONLY is:" + state.equals(Environment.MEDIA_MOUNTED_READ_ONLY));
		Log.d(TAG, "state.equals(Environment.MEDIA_SHARED is:" + state.equals(Environment.MEDIA_SHARED));
	}
	
	public String getStoragePath(Context mContext, boolean is_removale) { 
		StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
		Class<?> storageVolumeClazz = null;
		try {
			storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
			Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
			Method getPath = storageVolumeClazz.getMethod("getPath");
			Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
			Object resultObject = getVolumeList.invoke(mStorageManager);
			final int length = Array.getLength(resultObject);
			for (int i = 0; i < length; i++) {
				Object storageVolumeElement = Array.get(resultObject, i);
				 String path = (String) getPath.invoke(storageVolumeElement);
				 boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
				 if (is_removale == removable) {
					if (is_removale) {
					    result += "sdcard外部儲存路經" + path + "\n";
					    outSdcaraPath = path;
					} else {
					    result += "sdcard內部儲存路經" + path + "\n";
					    inSdcardPath = path;
					}
					return path;
				 }
			}
	    } catch (ClassNotFoundException e) {
	    	e.printStackTrace();
		} catch (InvocationTargetException e) {
		    e.printStackTrace();
		} catch (NoSuchMethodException e) {
		    e.printStackTrace();
		} catch (IllegalAccessException e) {
		    e.printStackTrace();
		}
		return null;
	}
	
	
	public void showSdCard() {
		//String sdcardPath = System.getenv("EXTERNAL_STORAGE");
		String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		result += "sdcard內部儲存路經" + sdcardPath + "\n";
		String extSdcardPaht = System.getenv("SECONDARY_STORAGE");
		result += "sdcard外部儲存路經" + extSdcardPaht + "\n";
		
	}
    /** 
     * 得到外部儲存可用的空間 
     * @return 剩餘空間的大小,單位是Byte 
     */  
    public long getExternalStoreAvailableSize(){  
    	String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_SHARED)) {  
            // 取得sdcard檔案路徑  
            File pathFile = Environment.getExternalStorageDirectory();  
            android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());  
            // 獲取SDCard上每個block的SIZE  
            long nBlocSize = statfs.getBlockSize();  
            // 獲取可供程式使用的Block的數量  
            long nAvailaBlock = statfs.getAvailableBlocks();  
            // 計算 SDCard 剩餘大小Byte  
            long nSDFreeSize = nAvailaBlock * nBlocSize ;
            if (nSDFreeSize > 1024 * 1024 * 1024) {
            	result += "外部儲存可用的空間:" + nSDFreeSize/(1024 * 1024 * 1024) + "G\n";
            } else {
            	result += "外部儲存可用的空間:" + nSDFreeSize + "Byte\n";
            }
            return nSDFreeSize;  
        } else {
        	result += "size:" + "0" + "\n";
        }
        return 0;  
    } 
    
//    public void checkPerssiom() {
//    	if (Build.VERSION.SDK_INT >= 23) { 
//    		 int REQUEST_CODE_CONTACT = 101;
//       		 String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; 
//       		 //驗證是否許可許可權               
//       		 for (String str : permissions) {                  
//       			 if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {   
//       				 //申請許可權                       
//       				 this.requestPermissions(permissions, REQUEST_CODE_CONTACT); 
//       				 return;
//       			 } else {
//       				 Log.d(TAG, "this.checkSelfPermission(str) == PackageManager.PERMISSION_GRANTED");
//       			 }
//       	    } 
//    	}
//	}
    
    public void getCommonPath() {
    	File file = Environment.getExternalStorageDirectory();
    	String path = file.getAbsolutePath();
    	result += "sdcard儲存路經" + path + "\n";
    	mTv.post(new Runnable(){
			@Override
			public void run() {
				mTv.setText(result);
			}
		});
    }
    public void saveDataToSdcard(String path, String fileName) {
    	if ("".equals(path) || path == null) {
    		result += "path is null or ''" + "\n";
    		mTv.post(new Runnable(){
				@Override
				public void run() {
					mTv.setText(result);
				}
    		});
    		return;
    	} 
    	String str = "sangfor";
		File sdDire = Environment.getExternalStorageDirectory();
		FileOutputStream outFileStream;
		try {
			outFileStream = new FileOutputStream(path + File.separator + fileName);
			outFileStream.write(str.getBytes());
			outFileStream.close();                  
			Toast.makeText(MainActivity.this, fileName +"檔案儲存成功", Toast.LENGTH_LONG).show(); 
		} catch (Exception e) {
			e.printStackTrace();
			result += "save " + fileName +"fail" + "\n";
			mTv.post(new Runnable(){
				@Override
				public void run() {
					mTv.setText(result);
				}
    		});
			Log.e(TAG, "save file fail");
		} 
    }
}