एक हटाने योग्य एसडी कार्ड का स्थान ढूंढें


204

क्या बाहरी एसडी कार्ड का स्थान खोजने का एक सार्वभौमिक तरीका है?

कृपया, बाहरी संग्रहण से भ्रमित न हों ।

Environment.getExternalStorageState()आंतरिक एसडी माउंट पॉइंट के लिए रास्ता देता है, जैसे "/ mnt / sdcard"। लेकिन सवाल बाहरी एसडी के बारे में है। मुझे "/ mnt / sdcard / external_sd" जैसा रास्ता कैसे मिलेगा (यह डिवाइस से डिवाइस में भिन्न हो सकता है)?

मुझे लगता है कि मैं mountफाइल सिस्टम नाम से कमांड के आउटपुट को फ़िल्टर करने के साथ समाप्त कर दूंगा । लेकिन मुझे यकीन नहीं है कि यह रास्ता काफी मजबूत है।


यहाँ मेरा समाधान है जो नौगट तक काम करता है: stackoverflow.com/a/40205116/5002496
गोकुल NC

'Environment.getExternalStorageState () आंतरिक एसडी माउंट पॉइंट जैसे "/ mnt / sdcard" के लिए पथ देता है। खैर, यह इस मायने में आंतरिक नहीं है कि एंड्रॉइड शब्द का उपयोग करता है। मेरा मानना ​​है कि आप जिस पद की तलाश कर रहे हैं वह "हटाने योग्य नहीं है।"
लार्स

जवाबों:


162

Environment.getExternalStorageState() आंतरिक एसडी माउंट पॉइंट जैसे "/ mnt / sdcard" पर वापसी

नहीं, Environment.getExternalStorageDirectory()जो भी उपकरण निर्माता को "बाहरी भंडारण" माना जाता है। कुछ उपकरणों पर, यह एक एसडी कार्ड की तरह हटाने योग्य मीडिया है। कुछ उपकरणों पर, यह ऑन-डिवाइस फ्लैश का एक हिस्सा है। यहां, "बाहरी भंडारण" का अर्थ है "होस्ट मशीन पर घुड़सवार होने पर यूएसबी मास स्टोरेज मोड के माध्यम से सुलभ सामान", कम से कम एंड्रॉइड 1.x और 2.x के लिए।

लेकिन सवाल बाहरी एसडी के बारे में है। "/ Mnt / sdcard / external_sd" जैसा रास्ता कैसे प्राप्त करें (यह डिवाइस से डिवाइस में भिन्न हो सकता है)?

एंड्रॉइड में "बाहरी एसडी" की कोई अवधारणा नहीं है, जो बाहरी भंडारण से अलग है, जैसा कि ऊपर वर्णित है।

यदि डिवाइस निर्माता ने बाहरी भंडारण के लिए बोर्ड-ऑन फ्लैश का चुनाव किया है और उसके पास एसडी कार्ड है, तो आपको यह निर्धारित करने के लिए उस निर्माता से संपर्क करना होगा कि आप एसडी कार्ड का उपयोग कर सकते हैं या नहीं (गारंटी नहीं) और इसके लिए क्या नियम हैं इसका उपयोग करना, जैसे कि इसके लिए किस मार्ग का उपयोग करना है।


अपडेट करें

नोट की दो हालिया बातें:

सबसे पहले, Android 4.4+ पर, आप हटाने योग्य मीडिया (जैसे, "बाहरी एसडी") के लिए लेखन पहुँच, कि मीडिया कि द्वारा दिया जा सकता है पर किसी भी स्थान के लिए छोड़कर नहीं है getExternalFilesDirs()और getExternalCacheDirs()डेव स्मिथ का उत्कृष्ट विश्लेषण देखें , खासकर यदि आप निम्न-स्तरीय विवरण चाहते हैं।

दूसरा, किसी को भी इस बात से वंचित करना कि मीडिया पहुंच से दूर है या नहीं, यह एंड्रॉयड एसडीके का हिस्सा है, यहां डायने हैकरबोर्न का आकलन है :

... ध्यान रखें: Android 4.4 जब तक, आधिकारिक Android मंच पर समर्थन नहीं किया है एसडी कार्ड सभी दो विशेष मामलों को छोड़कर: पुराने स्कूल भंडारण लेआउट जहां बाह्य भंडारण एक एसडी कार्ड (जो आज भी मंच द्वारा समर्थित है) है , और एंड्रॉइड 3.0 में एक छोटी सी सुविधा जोड़ी गई जहां यह अतिरिक्त एसडी कार्ड को स्कैन करेगा और उन्हें मीडिया प्रदाता में जोड़ देगा और एप्लिकेशन को केवल उनकी फाइलों तक पहुंच प्रदान करेगा (जो आज भी प्लेटफ़ॉर्म में समर्थित है)।

एंड्रॉइड 4.4 प्लेटफ़ॉर्म की पहली रिलीज़ है जिसने वास्तव में एसडी कार्ड को स्टोरेज के लिए उपयोग करने की अनुमति दी है। इससे पहले उनकी कोई भी पहुंच निजी, असमर्थित एपीआई के माध्यम से थी। अब हमारे पास प्लेटफ़ॉर्म में एक काफी समृद्ध एपीआई है जो अनुप्रयोगों को एसडी कार्ड के उपयोग को एक समर्थित तरीके से करने की अनुमति देता है, इससे पहले कि वे बेहतर तरीके से कर सकें: वे किसी भी आवश्यकता के बिना अपने ऐप-विशिष्ट भंडारण क्षेत्र का मुफ्त उपयोग कर सकते हैं एप्लिकेशन में अनुमतियाँ, और एसडी कार्ड पर किसी भी अन्य फ़ाइलों तक पहुँच सकते हैं जब तक वे फ़ाइल पिकर के माध्यम से जाते हैं, फिर से बिना किसी विशेष अनुमति की आवश्यकता के।


4
और यह समस्या एक समस्या बनती जा रही है क्योंकि HC और ICS डिवाइसेज़ उस बिंदु "एक्सट्रॉस्टोरेजडायरेक्टरी" से बाहर आते हैं और बाकी सब कुछ इसे आंतरिक भौतिक भंडारण की तरह। इसे बंद कर दें कि अधिकांश उपयोगकर्ताओं के पास यह पता लगाने के लिए कोई सुराग नहीं है कि फाइल सिस्टम में उनका एसडीकार्ड कहां है।
टोनी मारो

283
तो आपका जवाब मूल रूप से 'निर्माता से संपर्क करें' है। उपयोगी नहीं।
ड्रैगनट्रॉट

6
उत्तर का अंतिम भाग काफी सटीक नहीं है - एसडी कार्ड पथ का पता लगाने के लिए यह संभव है कि नीचे दिए गए उत्तरों का पालन करके (स्कैनिंग / proc / mounts, /system/etc/vold.fstab, आदि ...)।
OpenGL ES

8
@CommonsWare: फिर भी, यह अभी भी सटीक नहीं है कि किसी निर्माता से संपर्क करने के लिए किसी को "ज़रूरत" हो, जब कोई समाधान हो जो कई उपकरणों पर काम करता है, और इसके अलावा, एसडीके खुद सभी उपकरणों पर संगत नहीं है ताकि कोई गारंटी न हो। यहां तक ​​कि अगर ये समाधान सभी उपकरणों पर काम नहीं करते हैं, तो वे पर्याप्त उपकरणों पर काम करते हैं जो बाजार के कई एंड्रॉइड ऐप बाहरी एसडी कार्ड पथ का पता लगाने के लिए इन तकनीकों पर भरोसा करते हैं। मुझे लगता है कि यह सभी डेवलपर्स को मूर्ख कहने के लिए थोड़ा कठोर और समय से पहले है - क्या ग्राहक निश्चित रूप से उस का अंतिम न्यायाधीश नहीं है?
OpenGL ES

5
@CommonsWare यह काफी उचित है, जैसा कि चीजें जाती हैं। मैं आपसे निश्चित रूप से सहमत हूं कि एक डेवलपर यह नहीं मान सकता है कि यह हमेशा हर जगह काम करेगा, और यह कि किसी भी तरह के कोड को सभी उपकरणों या एंड्रॉइड के सभी संस्करणों पर काम करने की गारंटी नहीं दी जा सकती है। उम्मीद है कि यह एसडीके में तय हो जाता है! इस बीच, अभी भी विकल्प हैं जो कई उपकरणों पर काम करते हैं और एंड-यूज़र अनुभव में सुधार कर सकते हैं, और 80% सफलता और 0% सफलता के बीच विकल्प को देखते हुए मैं 80% ले लूंगा।
OpenGL ES

64

मैं यहां पाए गए कुछ उत्तरों के आधार पर निम्नलिखित समाधान के साथ आया हूं।

कोड:

public class ExternalStorage {

    public static final String SD_CARD = "sdCard";
    public static final String EXTERNAL_SD_CARD = "externalSdCard";

    /**
     * @return True if the external storage is available. False otherwise.
     */
    public static boolean isAvailable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

    public static String getSdCardPath() {
        return Environment.getExternalStorageDirectory().getPath() + "/";
    }

    /**
     * @return True if the external storage is writable. False otherwise.
     */
    public static boolean isWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;

    }

    /**
     * @return A map of all storage locations available
     */
    public static Map<String, File> getAllStorageLocations() {
        Map<String, File> map = new HashMap<String, File>(10);

        List<String> mMounts = new ArrayList<String>(10);
        List<String> mVold = new ArrayList<String>(10);
        mMounts.add("/mnt/sdcard");
        mVold.add("/mnt/sdcard");

        try {
            File mountFile = new File("/proc/mounts");
            if(mountFile.exists()){
                Scanner scanner = new Scanner(mountFile);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith("/dev/block/vold/")) {
                        String[] lineElements = line.split(" ");
                        String element = lineElements[1];

                        // don't add the default mount path
                        // it's already in the list.
                        if (!element.equals("/mnt/sdcard"))
                            mMounts.add(element);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            File voldFile = new File("/system/etc/vold.fstab");
            if(voldFile.exists()){
                Scanner scanner = new Scanner(voldFile);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith("dev_mount")) {
                        String[] lineElements = line.split(" ");
                        String element = lineElements[2];

                        if (element.contains(":"))
                            element = element.substring(0, element.indexOf(":"));
                        if (!element.equals("/mnt/sdcard"))
                            mVold.add(element);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        for (int i = 0; i < mMounts.size(); i++) {
            String mount = mMounts.get(i);
            if (!mVold.contains(mount))
                mMounts.remove(i--);
        }
        mVold.clear();

        List<String> mountHash = new ArrayList<String>(10);

        for(String mount : mMounts){
            File root = new File(mount);
            if (root.exists() && root.isDirectory() && root.canWrite()) {
                File[] list = root.listFiles();
                String hash = "[";
                if(list!=null){
                    for(File f : list){
                        hash += f.getName().hashCode()+":"+f.length()+", ";
                    }
                }
                hash += "]";
                if(!mountHash.contains(hash)){
                    String key = SD_CARD + "_" + map.size();
                    if (map.size() == 0) {
                        key = SD_CARD;
                    } else if (map.size() == 1) {
                        key = EXTERNAL_SD_CARD;
                    }
                    mountHash.add(hash);
                    map.put(key, root);
                }
            }
        }

        mMounts.clear();

        if(map.isEmpty()){
                 map.put(SD_CARD, Environment.getExternalStorageDirectory());
        }
        return map;
    }
}

उपयोग:

Map<String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard = externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);

1
nexus 4, nexus s, galaxy s2, galaxy s3, htc इच्छा =) के साथ परीक्षण किया गया
रिचर्ड

2
हाय फिर, रिचर्ड - विश्वास करो या नहीं, मुझे पूछना होगा: क्या आपने वास्तव में इस तरह से एक फ़ाइल में वापस लिखने और पढ़ने की कोशिश की थी, न कि केवल डायर प्राप्त करने के लिए? हमारे पुराने "/ sdcard0" मुद्दे को याद करें? मैंने इस कोड की कोशिश की और यह एक S3 पर विफल रहा जब मैंने उस फाइल में वापस पढ़ने की कोशिश की जो उसने लिखी थी। ... यह बहुत विचित्र है ... और दर्दनाक :))
हावर्ड पुतज

10
यह उन उपकरणों पर विफल रहता है जिनमें 2 एसडी कार्ड नहीं हैं। यह माना जाता है कि 1 पाया आंतरिक है, और 2 पाया बाहरी है ...
कैनर

नेक्सस 5 और नेक्सस 7. पर ओटीजी केबल के माध्यम से संलग्न यूएसबी उपकरणों के लिए काम नहीं किया था
खरवार रजा

4
/system/etc/vold.fstab एंड्रॉइड 4.3+
अली

37

मेरे पास एक एप्लिकेशन था जो एक ListPreferenceउपयोगकर्ता का उपयोग करता था जहां उस स्थान का चयन करना आवश्यक था जहां वे कुछ सहेजना चाहते थे।

उस ऐप में, मैंने स्कैन किया /proc/mountsऔर /system/etc/vold.fstabsdcard माउंट पॉइंट्स के लिए। मैंने प्रत्येक फ़ाइल से आरोह बिंदुओं को दो अलग-अलग ArrayLists में संग्रहीत किया है ।

फिर, मैंने एक सूची की तुलना अन्य और त्याग की गई वस्तुओं के साथ की जो दोनों सूचियों में नहीं थीं। इसने मुझे प्रत्येक sdcard के रूट रास्तों की एक सूची दी।

वहाँ से, मैं साथ रास्ते का परीक्षण किया File.exists(), File.isDirectory()और File.canWrite()। यदि उनमें से कोई भी परीक्षण गलत था, तो मैंने सूची से वह रास्ता छोड़ दिया।

सूची में जो कुछ भी बचा था, मैंने एक String[]सरणी में बदल दिया ताकि इसका उपयोग ListPreferenceमान विशेषता द्वारा किया जा सके ।

आप यहां कोड देख सकते हैं: http://sapienmobile.com/?p=204


FYI करें, यह Galaxy S3, 2 SD कार्ड पर काम नहीं करता है, केवल एक vold.conf में सूचीबद्ध है
3c71

1
@ 3c71 - क्या आप मुझे गैलेक्सी S3 के लिए vold और mounts फाइल भेज सकते हैं? मैं इसे कवर करने के लिए कोड को ट्विक करूंगा।
बैरन

गैलेक्सी एस, जो सभी रास्ते पाए गए वे लिखने योग्य नहीं थे, अजीब थे। दो संग्रहण पाए गए, डिफ़ॉल्ट / mnt / sdcard और / storage / sdcard0, दोनों परीक्षण करने में विफल रहे
पांचवें

1
मैंने mounts फ़ाइल को अनदेखा करने के लिए कोड को ट्विक किया है। मोटोरोला और सैमसंग उपकरणों पर यह मुद्दा था। माउंट फाइल ने external_sd केस को कवर नहीं किया, लेकिन यह IS vold में सूचीबद्ध है। मेरी कक्षा के आरंभिक संस्करण ने vold और त्याग की गई वस्तुओं के साथ mounts की तुलना की जो दोनों के लिए सामान्य नहीं थे। ऊपर दिए गए उसी लिंक से अद्यतन वर्ग को पकड़ो।
बैरन

1
धन्यवाद बैरन, यह "उत्तर" है; कम से कम उपयोगी है।
पस्तोपानी

23

आप ContextCompat.getExternalFilesDirs () नामक समर्थन लाइब्रेरी फ़ंक्शन का उपयोग करने का प्रयास कर सकते हैं :

      final File[] appsDir=ContextCompat.getExternalFilesDirs(getActivity(),null);
      final ArrayList<File> extRootPaths=new ArrayList<>();
      for(final File file : appsDir)
        extRootPaths.add(file.getParentFile().getParentFile().getParentFile().getParentFile());

पहला एक प्राथमिक बाहरी भंडारण है, और बाकी वास्तविक एसडी-कार्ड पथ हैं।

एकाधिक ".getParentFile ()" का कारण मूल पथ है, के बाद से किसी अन्य फ़ोल्डर में जाना है

.../Android/data/YOUR_APP_PACKAGE_NAME/files/

संपादित करें: यहाँ एक और अधिक व्यापक तरीका है जो मैंने बनाया है, एसडी कार्ड पथ प्राप्त करने के लिए:

  /**
   * returns a list of all available sd cards paths, or null if not found.
   *
   * @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
   */
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public static List<String> getSdCardPaths(final Context context, final boolean includePrimaryExternalStorage)
    {
    final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
    if(externalCacheDirs==null||externalCacheDirs.length==0)
      return null;
    if(externalCacheDirs.length==1)
      {
      if(externalCacheDirs[0]==null)
        return null;
      final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
      if(!Environment.MEDIA_MOUNTED.equals(storageState))
        return null;
      if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
        return null;
      }
    final List<String> result=new ArrayList<>();
    if(includePrimaryExternalStorage||externalCacheDirs.length==1)
      result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
    for(int i=1;i<externalCacheDirs.length;++i)
      {
      final File file=externalCacheDirs[i];
      if(file==null)
        continue;
      final String storageState=EnvironmentCompat.getStorageState(file);
      if(Environment.MEDIA_MOUNTED.equals(storageState))
        result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
      }
    if(result.isEmpty())
      return null;
    return result;
    }

  /** Given any file/folder inside an sd card, this will return the path of the sd card */
  private static String getRootOfInnerSdCardFolder(File file)
    {
    if(file==null)
      return null;
    final long totalSpace=file.getTotalSpace();
    while(true)
      {
      final File parentFile=file.getParentFile();
      if(parentFile==null||parentFile.getTotalSpace()!=totalSpace||!parentFile.canRead())
        return file.getAbsolutePath();
      file=parentFile;
      }
    }

यह एक बहुत अच्छा जवाब है, लेकिन कोई इसे एक साधारण गतिविधि में कैसे एकीकृत करेगा? वहाँ से परिभाषित नहीं कई चर, की तरह हैं App, ContextCompact,EnvironmentCompact
एंटोनियो

@Antonio ContextCompact, EnvironmentCompact समर्थन पुस्तकालय के माध्यम से उपलब्ध हैं। "App.global ()" केवल अनुप्रयोग संदर्भ है, जिसे मैंने वैश्विक रूप से सेट किया है क्योंकि मुझे हर जगह एक संदर्भ पैरामीटर जोड़ना पसंद नहीं है।
एंड्रॉयड डेवलपर

1
महान! मेरा डिवाइस v4.4 सैमसंग जीटी एस एडवांस के लिए काम करता है, आशा है कि यह दूसरों के लिए काम कर रहा होगा
user25

@androiddeveloper क्या सभी डिवाइस और एसडी कार्ड साइज़ के लिए संपादित जवाब काम करेगा?
राहुलरात्रि २६०२

1
यह मेरे लिए पूरी तरह से काम किया - स्वीकृत उत्तर होना चाहिए।
विरोधाभास

17

सभी बाहरी स्टोरेज (चाहे वे एसडी कार्ड हों या आंतरिक नॉन-रिमूवेबल स्टोरेज ) को पुनः प्राप्त करने के लिए , आप निम्नलिखित कोड का उपयोग कर सकते हैं:

final String state = Environment.getExternalStorageState();

if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) {  // we can read the External Storage...           
    //Retrieve the primary External Storage:
    final File primaryExternalStorage = Environment.getExternalStorageDirectory();

    //Retrieve the External Storages root directory:
    final String externalStorageRootDir;
    if ( (externalStorageRootDir = primaryExternalStorage.getParent()) == null ) {  // no parent...
        Log.d(TAG, "External Storage: " + primaryExternalStorage + "\n");
    }
    else {
        final File externalStorageRoot = new File( externalStorageRootDir );
        final File[] files = externalStorageRoot.listFiles();

        for ( final File file : files ) {
            if ( file.isDirectory() && file.canRead() && (file.listFiles().length > 0) ) {  // it is a real directory (not a USB drive)...
                Log.d(TAG, "External Storage: " + file.getAbsolutePath() + "\n");
            }
        }
    }
}

वैकल्पिक रूप से, आप का उपयोग कर सकते System.getenv ( "EXTERNAL_STORAGE") प्राथमिक बाह्य संग्रह डायरेक्ट्री पुनः प्राप्त करने (जैसे "/ भंडारण / sdcard0" ) और System.getenv ( "SECONDARY_STORAGE") सभी माध्यमिक निर्देशिका की सूची retieve लिए (उदाहरण के लिए " / संग्रहण / extSdCard: / संग्रहण / UsbDriveA: / संग्रहण / UsbDriveB " )। याद रखें कि, इस मामले में भी, आप USB ड्राइव को बाहर करने के लिए द्वितीयक निर्देशिकाओं की सूची को फ़िल्टर करना चाह सकते हैं।

किसी भी मामले में, कृपया ध्यान दें कि हार्ड-कोडेड रास्तों का उपयोग करना हमेशा एक बुरा दृष्टिकोण होता है (स्पष्ट रूप से जब प्रत्येक निर्माता इसे प्रसन्नता के रूप में बदल सकता है)।


2
बस किसी भी डाउनवॉटर पर विचार करें जो एक टिप्पणी को ट्रोल नहीं छोड़ता है, इसलिए मैंने इसकी क्षतिपूर्ति की। ;) लेकिन, मुझे लगता है कि आपके तरीके के बजाय मनमाना है: हम कैसे जान सकते हैं कि उन "यूएसबी ड्राइव" को छोड़ देना लेकिन बाकी सब वास्तव में "sdcards" के बराबर है, जैसा कि सवाल में पूछा गया है? इसके अलावा आपका सुझाव System.getenv("SECONDARY_STORAGE")कुछ संदर्भों के साथ भी हो सकता है, क्योंकि यह अनिर्दिष्ट लगता है।
एस.जे.

1
जहां तक ​​मुझे पता है, एंड्रॉइड एपीआई में सभी बाहरी स्टोरेज को पुनः प्राप्त करने के लिए एक मानक विधि का कोई संदर्भ नहीं है। हालांकि, प्रस्तावित विधि बिल्कुल भी मनमानी नहीं है। एंड्रॉइड में, हर यूनिक्स / लिनक्स सिस्टम की तरह, सभी बढ़ते भंडारण उपकरणों को एक आम निर्देशिका में संग्रहीत / लिंक किया जाता है: "/ mnt" (बढ़ते भंडारण उपकरणों के लिए मानक यूनिक्स / लिनक्स निर्देशिका) या, नवीनतम संस्करणों में, "/ भंडारण "। यही कारण है कि आप पूरी तरह से सुनिश्चित हो सकते हैं कि आपको इस फ़ोल्डर में सभी एसडी कार्ड मिलेंगे।
पाओलो रूवेल्ली

1
System.getenv ("EXTERNAL_STORAGE") विधि के बारे में, मेरे पास API पृष्ठ (जो बहुत कुछ नहीं समझाता) के बजाय कोई संदर्भ नहीं है: developer.android.com/reference/java/lang// मुझे कोई भी नहीं मिला। एंड्रॉइड सिस्टम पर्यावरण चर के लिए आधिकारिक पृष्ठ। यहाँ, हालाँकि, आप उनमें से एक छोटी सूची पा सकते हैं: herongyang.com/Android/…
पाओलो

एसडीकार्ड के बारे में निश्चित नहीं होने का मेरा मतलब यह है कि /mntएसडी कार्ड और यूएसबी ड्राइव ही नहीं, बल्कि कई अन्य एफएस ट्री भी हो सकते हैं। आपका कोड किसी भी आंतरिक (शायद आभासी भी) फाइलसिस्टम आरोह को सूचीबद्ध करेगा, अगर मैं इसे सही समझता हूं, जबकि प्रश्न केवल sdcards चाहता है ।
एस.जे.

1
समझा। हाँ आप सही है। मेरी विधि से आप आंतरिक (गैर-हटाने योग्य) एसडी यादों को भी पुनः प्राप्त करेंगे।
पाओलो रूवेली २१'१४

15

रिचर्ड की तरह मैं भी उपलब्ध भंडारण विकल्पों की सूची प्राप्त करने के लिए फ़ाइल का उपयोग / खरीद / करता है

public class StorageUtils {

    private static final String TAG = "StorageUtils";

    public static class StorageInfo {

        public final String path;
        public final boolean internal;
        public final boolean readonly;
        public final int display_number;

        StorageInfo(String path, boolean internal, boolean readonly, int display_number) {
            this.path = path;
            this.internal = internal;
            this.readonly = readonly;
            this.display_number = display_number;
        }

        public String getDisplayName() {
            StringBuilder res = new StringBuilder();
            if (internal) {
                res.append("Internal SD card");
            } else if (display_number > 1) {
                res.append("SD card " + display_number);
            } else {
                res.append("SD card");
            }
            if (readonly) {
                res.append(" (Read only)");
            }
            return res.toString();
        }
    }

    public static List<StorageInfo> getStorageList() {

        List<StorageInfo> list = new ArrayList<StorageInfo>();
        String def_path = Environment.getExternalStorageDirectory().getPath();
        boolean def_path_internal = !Environment.isExternalStorageRemovable();
        String def_path_state = Environment.getExternalStorageState();
        boolean def_path_available = def_path_state.equals(Environment.MEDIA_MOUNTED)
                                    || def_path_state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
        boolean def_path_readonly = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
        BufferedReader buf_reader = null;
        try {
            HashSet<String> paths = new HashSet<String>();
            buf_reader = new BufferedReader(new FileReader("/proc/mounts"));
            String line;
            int cur_display_number = 1;
            Log.d(TAG, "/proc/mounts");
            while ((line = buf_reader.readLine()) != null) {
                Log.d(TAG, line);
                if (line.contains("vfat") || line.contains("/mnt")) {
                    StringTokenizer tokens = new StringTokenizer(line, " ");
                    String unused = tokens.nextToken(); //device
                    String mount_point = tokens.nextToken(); //mount point
                    if (paths.contains(mount_point)) {
                        continue;
                    }
                    unused = tokens.nextToken(); //file system
                    List<String> flags = Arrays.asList(tokens.nextToken().split(",")); //flags
                    boolean readonly = flags.contains("ro");

                    if (mount_point.equals(def_path)) {
                        paths.add(def_path);
                        list.add(0, new StorageInfo(def_path, def_path_internal, readonly, -1));
                    } else if (line.contains("/dev/block/vold")) {
                        if (!line.contains("/mnt/secure")
                            && !line.contains("/mnt/asec")
                            && !line.contains("/mnt/obb")
                            && !line.contains("/dev/mapper")
                            && !line.contains("tmpfs")) {
                            paths.add(mount_point);
                            list.add(new StorageInfo(mount_point, false, readonly, cur_display_number++));
                        }
                    }
                }
            }

            if (!paths.contains(def_path) && def_path_available) {
                list.add(0, new StorageInfo(def_path, def_path_internal, def_path_readonly, -1));
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (buf_reader != null) {
                try {
                    buf_reader.close();
                } catch (IOException ex) {}
            }
        }
        return list;
    }    
}

धन्यवाद। पूरी तरह से काम किया। और मुझे पसंद है कि आपने StorageInfo को नॉन म्यूटेबल बनाया। दूसरी ओर printStackTrace? जब हमारे पास है android.util.Log.e?
मार्टिन

1
नेक्सस 5 और नेक्सस 7. पर ओटीजी केबल के माध्यम से संलग्न यूएसबी उपकरणों के लिए काम नहीं किया था
खरवार रजा

1
मैं SDCard पर फाइल लिखने के लिए इसका उपयोग नहीं कर सकता
Eu Vid

@EuVid वीएम / एवीडी पर काम करता है लेकिन हार्डवेयर पर नहीं
जासूस

11

यह पता लगाना संभव है कि रीडिंग /proc/mounts(मानक लिनक्स फ़ाइल) और वॉल्ड डेटा ( /system/etc/vold.conf) के खिलाफ क्रॉस-चेकिंग द्वारा किसी भी अतिरिक्त एसडी कार्ड को कहां रखा गया है । और ध्यान दें, कि लौटाया गया स्थान Environment.getExternalStorageDirectory()vold कॉन्फ़िगरेशन में नहीं दिखाई दे सकता है (कुछ डिवाइसों में यह आंतरिक संग्रहण है जो अनमाउंट नहीं किया जा सकता है), लेकिन फिर भी इसे सूची में शामिल करना होगा। हालाँकि, हमें उपयोगकर्ता के लिए उनका वर्णन करने का एक अच्छा तरीका नहीं मिला ।


Imo, का उपयोग फाइलसिस्टम mountपढ़ने की तुलना में अधिक संगत है /proc। समस्या यह है कि एसडी कार्ड एफएटी के रूप में आवश्यक नहीं है। इसके अलावा, कार्ड माउंट बिंदु ROM से ROM में भिन्न हो सकता है। इसके अलावा, कई अन्य VFAT विभाजन हो सकते हैं ...
बोरिसट्रस्ट

1
@borisstr: एचएम, वास्तव में एंड्रॉइड vold का उपयोग करता है , इसलिए इसे देखने के साथ-साथ यह उचित है।
Jan Hudec

ऊपर मेरे पोस्ट से साझा की गई कोड फ़ाइल में उपयोगकर्ता को खोजे गए रूट पथ का वर्णन करने की एक विधि शामिल है। को देखो setProperties () विधि।
बैरन

1
@borisstr, वास्तव में, नहीं, पढ़ना / proc / mounts mountनिष्पादन योग्य को लॉन्च करने की तुलना में Android उपकरणों पर अधिक पोर्टेबल है , विशेष रूप से लॉन्चिंग निष्पादन योग्य को हतोत्साहित करने के रूप में।
क्रिस स्ट्रैटन

7

मैं इस समय इस विषय के अंदर सभी समाधानों की कोशिश करता हूं। लेकिन उन सभी ने एक बाहरी (हटाने योग्य) और एक आंतरिक (नहीं-हटाने योग्य) कार्ड वाले उपकरणों पर सही ढंग से काम नहीं किया। बाहरी कार्ड का पथ संभव नहीं है '' माउंट '' कमांड से, 'प्रोक / माउंट' फाइल आदि से।

और मैं अपना स्वयं का समाधान बनाता हूं (पाउलो लुआन के) पर:

String sSDpath = null;
File   fileCur = null;
for( String sPathCur : Arrays.asList( "ext_card", "external_sd", "ext_sd", "external", "extSdCard",  "externalSdCard")) // external sdcard
{
   fileCur = new File( "/mnt/", sPathCur);
   if( fileCur.isDirectory() && fileCur.canWrite())
   {
     sSDpath = fileCur.getAbsolutePath();
     break;
   }
}
fileCur = null;
if( sSDpath == null)  sSDpath = Environment.getExternalStorageDirectory().getAbsolutePath();

6

यदि आप स्रोत कोड android.os.Environmentको देखते हैं तो आप देखेंगे कि Android पथों के लिए पर्यावरण चर पर बहुत निर्भर करता है। आप हटाने योग्य एसडी कार्ड के लिए रास्ता खोजने के लिए "SECONDARY_STORAGE" पर्यावरण चर का उपयोग कर सकते हैं।

/**
 * Get a file using an environmental variable.
 *
 * @param variableName
 *         The Environment variable name.
 * @param paths
 *         Any paths to the file if the Environment variable was not found.
 * @return the File or {@code null} if the File could not be located.
 */
private static File getDirectory(String variableName, String... paths) {
    String path = System.getenv(variableName);
    if (!TextUtils.isEmpty(path)) {
        if (path.contains(":")) {
            for (String _path : path.split(":")) {
                File file = new File(_path);
                if (file.exists()) {
                    return file;
                }
            }
        } else {
            File file = new File(path);
            if (file.exists()) {
                return file;
            }
        }
    }
    if (paths != null && paths.length > 0) {
        for (String _path : paths) {
            File file = new File(_path);
            if (file.exists()) {
                return file;
            }
        }
    }
    return null;
}

उदाहरण का उपयोग:

public static final File REMOVABLE_STORAGE = getDirectory("SECONDARY_STORAGE");

5

बस इसका उपयोग करें:

String primary_sd = System.getenv("EXTERNAL_STORAGE");
if(primary_sd != null)
    Log.i("EXTERNAL_STORAGE", primary_sd);
String secondary_sd = System.getenv("SECONDARY_STORAGE");
if(secondary_sd != null)
    Log.i("SECONDARY_STORAGE", secondary_sd)

कुछ उपकरणों पर SECONDARY_STORAGEएक बृहदान्त्र (":") के साथ कई पथ अलग हो जाते हैं। यही कारण है कि मैंने स्ट्रिंग को विभाजित किया (ऊपर मेरा उत्तर देखें)।
जेरेड रुम्मलर

ये दोनों मेरे लिए अशक्त लौटते हैं।
टिम कूपर

5

क्या बाहरी एसडी कार्ड का स्थान खोजने का एक सार्वभौमिक तरीका है?

तक सार्वभौमिक तरह से , आप सरकारी तरीका मतलब है; हाँ वहाँ एक है।

एपीआई स्तर 19 में यानी एंड्रॉइड वर्जन 4.4 किटकैट में, उन्होंने क्लास File[] getExternalFilesDirs (String type)में जोड़ा Contextहै जो ऐप्स को माइक्रो एसडी कार्ड में डेटा / फाइल स्टोर करने की अनुमति देता है।

एंड्रॉइड 4.4 प्लेटफ़ॉर्म की पहली रिलीज़ है जिसने वास्तव में ऐप्स को भंडारण के लिए एसडी कार्ड का उपयोग करने की अनुमति दी है। एपीआई स्तर 19 से पहले एसडी कार्ड की कोई भी पहुंच निजी, असमर्थित एपीआई के माध्यम से थी।

getExternalFilesDirs (स्ट्रिंग प्रकार) सभी साझा / बाहरी संग्रहण उपकरणों पर एप्लिकेशन-विशिष्ट निर्देशिकाओं के लिए पूर्ण पथ देता है। इसका मतलब है, यह आंतरिक और बाह्य मेमोरी दोनों के लिए रास्ते लौटाएगा। आम तौर पर, दूसरा लौटा पथ माइक्रोएसडी कार्ड (यदि कोई हो) के लिए भंडारण पथ होगा।

लेकिन ध्यान दें,

साझा संग्रहण हमेशा उपलब्ध नहीं हो सकता है, क्योंकि हटाने योग्य मीडिया को उपयोगकर्ता द्वारा हटाया जा सकता है। मीडिया स्थिति का उपयोग करके जाँच की जा सकती है getExternalStorageState(File)

इन फ़ाइलों के साथ कोई सुरक्षा लागू नहीं है। उदाहरण के लिए, कोई भी एप्लिकेशन होल्डिंग WRITE_EXTERNAL_STORAGEइन फ़ाइलों को लिख सकता है।

Google / आधिकारिक एंड्रॉइड डॉक्स के अनुसार आंतरिक और बाह्य संग्रहण शब्दावली हमारे विचार से काफी भिन्न है।


"Google / आधिकारिक एंड्रॉइड डॉक्स के अनुसार आंतरिक और बाह्य संग्रहण शब्दावली हमारे विचार से काफी भिन्न है।" हां, वास्तव में प्रश्न का शीर्षक स्पष्ट करता है कि ओपी एक हटाने योग्य एसडी कार्ड के बारे में पूछ रहा है । getExternalFilesDirs()अक्सर ऐसे एसडी कार्ड लौटाते हैं जो हटाने योग्य नहीं होते हैं, इसलिए नहीं, यह हटाने योग्य एसडी कार्ड का स्थान खोजने का एक सार्वभौमिक तरीका नहीं है।
लार्स

"getExternalFilesDirs (स्ट्रिंग प्रकार) सभी साझा / बाहरी संग्रहण उपकरणों पर एप्लिकेशन-विशिष्ट निर्देशिकाओं के लिए पूर्ण पथ देता है। इसका मतलब है, यह आंतरिक और बाह्य मेमोरी दोनों के लिए पथ लौटाएगा।" वाक्यों की यह जोड़ी बहुत ही भ्रामक है, क्योंकि उनके लिए दोनों सच होने के लिए, "बाहरी" का मतलब दो अलग और परस्पर विरोधी चीजों से है।
लार्स

4

यहां मैं बाहरी कार्ड खोजने का तरीका बताता हूं। माउंट cmd रिटर्न का उपयोग करें फिर vfat भाग को पार्स करें।

String s = "";
try {
Process process = new ProcessBuilder().command("mount")
        .redirectErrorStream(true).start();

process.waitFor();

InputStream is = process.getInputStream();
byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
    s = s + new String(buffer);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}

//用行分隔mount列表
String[] lines = s.split("\n");
for(int i=0; i<lines.length; i++) {
//如果行内有挂载路径且为vfat类型,说明可能是内置或者外置sd的挂载点
if(-1 != lines[i].indexOf(path[0]) && -1 != lines[i].indexOf("vfat")) {
    //再用空格分隔
    String[] blocks = lines[i].split("\\s");
    for(int j=0; j<blocks.length; j++) {
        //判断是否是挂载为vfat类型
        if(-1 != blocks[j].indexOf(path[0])) {
            //Test if it is the external sd card.
        }
    }
}
}

4

यह समाधान इस तथ्य को संभालता है कि System.getenv("SECONDARY_STORAGE")मार्शमैलो के साथ कोई फायदा नहीं है।

परीक्षण किया गया और इस पर काम किया जा रहा है:

  • सैमसंग गैलेक्सी टैब 2 (एंड्रॉयड 4.1.1 - स्टॉक)
  • सैमसंग गैलेक्सी नोट 8.0 (एंड्रॉयड 4.2.2 - स्टॉक)
  • सैमसंग गैलेक्सी एस 4 (एंड्रॉइड 4.4 - स्टॉक)
  • सैमसंग गैलेक्सी एस 4 (एंड्रॉइड 5.1.1 - सायनोजेनमॉड)
  • सैमसंग गैलेक्सी टैब ए (एंड्रॉइड 6.0.1 - स्टॉक)

    /**
     * Returns all available external SD-Card roots in the system.
     *
     * @return paths to all available external SD-Card roots in the system.
     */
    public static String[] getStorageDirectories() {
        String [] storageDirectories;
        String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            List<String> results = new ArrayList<String>();
            File[] externalDirs = applicationContext.getExternalFilesDirs(null);
            for (File file : externalDirs) {
                String path = file.getPath().split("/Android")[0];
                if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file))
                        || rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)){
                    results.add(path);
                }
            }
            storageDirectories = results.toArray(new String[0]);
        }else{
            final Set<String> rv = new HashSet<String>();
    
            if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
                final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
                Collections.addAll(rv, rawSecondaryStorages);
            }
            storageDirectories = rv.toArray(new String[rv.size()]);
        }
        return storageDirectories;
    }

2

ऊपर मेरे मूल उत्तर के बाद से, स्कैनिंग vold अब विभिन्न निर्माताओं में व्यवहार्य नहीं है।

मैंने एक अधिक विश्वसनीय और सीधे आगे की विधि विकसित की है।

File mnt = new File("/storage");
if (!mnt.exists())
    mnt = new File("/mnt");

File[] roots = mnt.listFiles(new FileFilter() {

    @Override
    public boolean accept(File pathname) {
        return pathname.isDirectory() && pathname.exists()
                && pathname.canWrite() && !pathname.isHidden()
                && !isSymlink(pathname);
    }
});

जड़ों में सिस्टम पर सभी लेखन योग्य रूट डाइरेक्टरी शामिल होंगी, जिसमें किसी भी USB से जुड़े usb डिवाइस शामिल हैं।

नोट: कैनरी विधि को android.permission.WRITE_EXTERNAL_STORAGE अनुमति की आवश्यकता है।


इस विधि को टाइप किया गया है (फाइल) नए फाइलफिल्टर () {} के लिए अपरिभाषित है
ओमिड ओमिडि

किसी भी विचार अगर यह एंड्रॉइड 4.4 पर कैनरी के कारण बाहरी एसडी कार्ड खोजने में विफल हो जाएगा?
एंथनी

यह निश्चित रूप से आपकी अन्य विधि की तुलना में अधिक सीधा है, लेकिन क्या यह विश्वसनीय है? जैसे मैंने पढ़ा है कि कुछ सैमसंग उपकरणों पर, /external_sdबाहरी माइक्रोएसडी कार्ड है; कुछ एलजी पर, यह /_ExternalSD; कुछ उपकरणों पर /sdcard। हो सकता है कि उत्तरार्द्ध एक /storage/sdcard0समरूप या समान है, लेकिन क्या ये अन्य वास्तव में मज़बूती से कवर होंगे /storage/*और /mount/*?
लार्स

इसके अलावा, pathname.canWrite()WRITE_EXTERNAL_STORAGE अनुमति का उपयोग करना और आवश्यक है ? सिर्फ कॉल क्यों नहीं pathname.canRead()?
लार्स

1

इतनी देर हो चुकी थी लेकिन आखिरकार मुझे कुछ मिला, मैंने ज्यादातर डिवाइसों (निर्माता और एंड्रॉइड वर्जन द्वारा) को एंड्रॉइड 2.2+ पर काम करने का परीक्षण किया है। यदि आपको लगता है कि यह काम नहीं कर रहा है, तो इसे अपने डिवाइस के नाम के साथ टिप्पणी करें। मैं इसे ठीक कर दूंगा। अगर कोई दिलचस्पी रखता है तो मैं बताऊंगा कि यह कैसे काम करता है।

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;

import android.util.Log;


/**
 * @author ajeet
 *05-Dec-2014  2014
 *
 */
public class StorageUtil {

    public boolean isRemovebleSDCardMounted() {
        File file = new File("/sys/class/block/");
        File[] files = file.listFiles(new MmcblkFilter("mmcblk\\d$"));
        boolean flag = false;
        for (File mmcfile : files) {
            File scrfile = new File(mmcfile, "device/scr");
            if (scrfile.exists()) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    public String getRemovebleSDCardPath() throws IOException {
        String sdpath = null;
        File file = new File("/sys/class/block/");
        File[] files = file.listFiles(new MmcblkFilter("mmcblk\\d$"));
        String sdcardDevfile = null;
        for (File mmcfile : files) {
            Log.d("SDCARD", mmcfile.getAbsolutePath());
            File scrfile = new File(mmcfile, "device/scr");
            if (scrfile.exists()) {
                sdcardDevfile = mmcfile.getName();
                Log.d("SDCARD", mmcfile.getName());
                break;
            }
        }
        if (sdcardDevfile == null) {
            return null;
        }
        FileInputStream is;
        BufferedReader reader;

        files = file.listFiles(new MmcblkFilter(sdcardDevfile + "p\\d+"));
        String deviceName = null;
        if (files.length > 0) {
            Log.d("SDCARD", files[0].getAbsolutePath());
            File devfile = new File(files[0], "dev");
            if (devfile.exists()) {
                FileInputStream fis = new FileInputStream(devfile);
                reader = new BufferedReader(new InputStreamReader(fis));
                String line = reader.readLine();
                deviceName = line;
            }
            Log.d("SDCARD", "" + deviceName);
            if (deviceName == null) {
                return null;
            }
            Log.d("SDCARD", deviceName);

            final File mountFile = new File("/proc/self/mountinfo");

            if (mountFile.exists()) {
                is = new FileInputStream(mountFile);
                reader = new BufferedReader(new InputStreamReader(is));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    // Log.d("SDCARD", line);
                    // line = reader.readLine();
                    // Log.d("SDCARD", line);
                    String[] mPonts = line.split("\\s+");
                    if (mPonts.length > 6) {
                        if (mPonts[2].trim().equalsIgnoreCase(deviceName)) {
                            if (mPonts[4].contains(".android_secure")
                                    || mPonts[4].contains("asec")) {
                                continue;
                            }
                            sdpath = mPonts[4];
                            Log.d("SDCARD", mPonts[4]);

                        }
                    }

                }
            }

        }

        return sdpath;
    }

    static class MmcblkFilter implements FilenameFilter {
        private String pattern;

        public MmcblkFilter(String pattern) {
            this.pattern = pattern;

        }

        @Override
        public boolean accept(File dir, String filename) {
            if (filename.matches(pattern)) {
                return true;
            }
            return false;
        }

    }

}

अरे नीच कृपया पहले प्रयास करें। यदि यह काम नहीं कर रहा है तो अपने डिवाइस पर टिप्पणी करें। हम इसे एंड्रॉइड 2.2+
Ajeet47

आपकी कक्षा मुझे Samsung Galaxy S4, GT-I9500, Android 5.0.1 (डिवाइस रूट नहीं है) पर मुझे / mnt / media_rw / extSdCard देता है। लेकिन ES फ़ाइल प्रबंधक के साथ फ़ोल्डर / mnt / media_rw में कुछ भी दिखाई नहीं दे रहा है ...
isabsent

@isabsent का उपयोग अगर (Build.VERSION.SDK_INT> = Build.VERSION_CODES.KITKAT) {फ़ाइल [] फ़ाइल = संदर्भ.getExternalFilesDirs (नल); वापसी file.length> 1; फाइल [1]: अशक्त; }
अजीत ४

क्या आप के बारे में सोचते हैं stackoverflow.com/a/27197248/753575 ? क्या यह दृष्टिकोण Build.VERSION.SDK_INT> = Build.VERSION_CODES.KITKAT के मामले के लिए अधिक व्यापक है?
दिलेर

हाँ। यह गारंटी है कि आपको संदर्भ से सार्थक रास्ता मिलता है ।getExternalFilesDirs (नल), लेकिन आपने इसे रूट पथ के लिए ट्रिम कर दिया है (यह आपके लिए ऐप निर्देशिका के लिए पथ वापस कर देगा। इसे "/ Android" पर ट्रिम करें)
Ajeet47

1

नीचे दिए गए कोड को लिखकर आपको स्थान मिलेगा:

/ भंडारण / 663D-554E / एंड्रॉयड / डेटा / app_package_name / फ़ाइलें /

जो आपके एप्लिकेशन डेटा को sd_card के अंदर / एंड्रॉइड / डेटा स्थान पर संग्रहीत करता है।

File[] list = ContextCompat.getExternalFilesDirs(MainActivity.this, null);

list[1]+"/fol" 

फ़ाइल सरणी के लिए sdcard के लिए आंतरिक और 1 के लिए स्थान पास 0 पाने के लिए।

मैंने इस कोड को एक मोटो जी 4 प्लस और सैमसंग डिवाइस (सभी ठीक काम करता है) पर परीक्षण किया है।

आशा है कि यह उपयोगी हो सकता है।


कभी-कभी sd कार्ड पथ इंडेक्स 1 पर नहीं है, मैंने उन मामलों को देखा है जहां यह इंडेक्स 0. पर था। कुछ और का पालन करने के लिए बेहतर है
राघव सत्यदेव

1

यहां मैं एक हटाने योग्य एसडी कार्ड खोजने के लिए विधि का उपयोग कर रहा हूं । यह जटिल है, और शायद कुछ स्थितियों के लिए ओवरकिल है, लेकिन यह एंड्रॉइड संस्करणों और डिवाइस निर्माताओं की एक विस्तृत विविधता पर काम करता है जिन्हें मैंने पिछले कुछ वर्षों में परीक्षण किया है। मुझे एपीआई स्तर 15 के बाद से किसी भी डिवाइस का पता नहीं है, जिस पर वह एसडी कार्ड नहीं ढूंढता है, अगर कोई माउंटेड है। यह ज्यादातर मामलों में गलत सकारात्मक रिटर्न नहीं करेगा, खासकर यदि आप इसे देखने के लिए एक ज्ञात फ़ाइल का नाम देते हैं।

कृपया मुझे बताएं कि क्या आप किसी ऐसे मामले में भाग लेते हैं जहां यह काम नहीं करता है।

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.regex.Pattern;

public class SDCard {
    private static final String TAG = "SDCard";

    /** In some scenarios we can expect to find a specified file or folder on SD cards designed
     * to work with this app. If so, set KNOWNFILE to that filename. It will make our job easier.
     * Set it to null otherwise. */
    private static final String KNOWNFILE = null;

    /** Common paths for microSD card. **/
    private static String[] commonPaths = {
            // Some of these taken from
            // /programming/13976982/removable-storage-external-sdcard-path-by-manufacturers
            // These are roughly in order such that the earlier ones, if they exist, are more sure
            // to be removable storage than the later ones.
            "/mnt/Removable/MicroSD",
            "/storage/removable/sdcard1", // !< Sony Xperia Z1
            "/Removable/MicroSD", // Asus ZenPad C
            "/removable/microsd",
            "/external_sd", // Samsung
            "/_ExternalSD", // some LGs
            "/storage/extSdCard", // later Samsung
            "/storage/extsdcard", // Main filesystem is case-sensitive; FAT isn't.
            "/mnt/extsd", // some Chinese tablets, e.g. Zeki
            "/storage/sdcard1", // If this exists it's more likely than sdcard0 to be removable.
            "/mnt/extSdCard",
            "/mnt/sdcard/external_sd",
            "/mnt/external_sd",
            "/storage/external_SD",
            "/storage/ext_sd", // HTC One Max
            "/mnt/sdcard/_ExternalSD",
            "/mnt/sdcard-ext",

            "/sdcard2", // HTC One M8s
            "/sdcard1", // Sony Xperia Z
            "/mnt/media_rw/sdcard1",   // 4.4.2 on CyanogenMod S3
            "/mnt/sdcard", // This can be built-in storage (non-removable).
            "/sdcard",
            "/storage/sdcard0",
            "/emmc",
            "/mnt/emmc",
            "/sdcard/sd",
            "/mnt/sdcard/bpemmctest",
            "/mnt/external1",
            "/data/sdext4",
            "/data/sdext3",
            "/data/sdext2",
            "/data/sdext",
            "/storage/microsd" //ASUS ZenFone 2

            // If we ever decide to support USB OTG storage, the following paths could be helpful:
            // An LG Nexus 5 apparently uses usb://1002/UsbStorage/ as a URI to access an SD
            // card over OTG cable. Other models, like Galaxy S5, use /storage/UsbDriveA
            //        "/mnt/usb_storage",
            //        "/mnt/UsbDriveA",
            //        "/mnt/UsbDriveB",
    };

    /** Find path to removable SD card. */
    public static File findSdCardPath(Context context) {
        String[] mountFields;
        BufferedReader bufferedReader = null;
        String lineRead = null;

        /** Possible SD card paths */
        LinkedHashSet<File> candidatePaths = new LinkedHashSet<>();

        /** Build a list of candidate paths, roughly in order of preference. That way if
         * we can't definitively detect removable storage, we at least can pick a more likely
         * candidate. */

        // Could do: use getExternalStorageState(File path), with and without an argument, when
        // available. With an argument is available since API level 21.
        // This may not be necessary, since we also check whether a directory exists and has contents,
        // which would fail if the external storage state is neither MOUNTED nor MOUNTED_READ_ONLY.

        // I moved hard-coded paths toward the end, but we need to make sure we put the ones in
        // backwards order that are returned by the OS. And make sure the iterators respect
        // the order!
        // This is because when multiple "external" storage paths are returned, it's always (in
        // experience, but not guaranteed by documentation) with internal/emulated storage
        // first, removable storage second.

        // Add value of environment variables as candidates, if set:
        // EXTERNAL_STORAGE, SECONDARY_STORAGE, EXTERNAL_SDCARD_STORAGE
        // But note they are *not* necessarily *removable* storage! Especially EXTERNAL_STORAGE.
        // And they are not documented (API) features. Typically useful only for old versions of Android.

        String val = System.getenv("SECONDARY_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);
        val = System.getenv("EXTERNAL_SDCARD_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);

        // Get listing of mounted devices with their properties.
        ArrayList<File> mountedPaths = new ArrayList<>();
        try {
            // Note: Despite restricting some access to /proc (http://stackoverflow.com/a/38728738/423105),
            // Android 7.0 does *not* block access to /proc/mounts, according to our test on George's Alcatel A30 GSM.
            bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));

            // Iterate over each line of the mounts listing.
            while ((lineRead = bufferedReader.readLine()) != null) {
                Log.d(TAG, "\nMounts line: " + lineRead);
                mountFields = lineRead.split(" ");

                // columns: device, mountpoint, fs type, options... Example:
                // /dev/block/vold/179:97 /storage/sdcard1 vfat rw,dirsync,nosuid,nodev,noexec,relatime,uid=1000,gid=1015,fmask=0002,dmask=0002,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0
                String device = mountFields[0], path = mountFields[1], fsType = mountFields[2];

                // The device, path, and fs type must conform to expected patterns.
                if (!(devicePattern.matcher(device).matches() &&
                        pathPattern.matcher(path).matches() &&
                        fsTypePattern.matcher(fsType).matches()) ||
                        // mtdblock is internal, I'm told.
                        device.contains("mtdblock") ||
                        // Check for disqualifying patterns in the path.
                        pathAntiPattern.matcher(path).matches()) {
                    // If this mounts line fails our tests, skip it.
                    continue;
                }

                // TODO maybe: check options to make sure it's mounted RW?
                // The answer at http://stackoverflow.com/a/13648873/423105 does.
                // But it hasn't seemed to be necessary so far in my testing.

                // This line met the criteria so far, so add it to candidate list.
                addPath(path, null, mountedPaths);
            }
        } catch (IOException ignored) {
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ignored) {
                }
            }
        }

        // Append the paths from mount table to candidate list, in reverse order.
        if (!mountedPaths.isEmpty()) {
            // See https://stackoverflow.com/a/5374346/423105 on why the following is necessary.
            // Basically, .toArray() needs its parameter to know what type of array to return.
            File[] mountedPathsArray = mountedPaths.toArray(new File[mountedPaths.size()]);
            addAncestors(candidatePaths, mountedPathsArray);
        }

        // Add hard-coded known common paths to candidate list:
        addStrings(candidatePaths, commonPaths);

        // If the above doesn't work we could try the following other options, but in my experience they
        // haven't added anything helpful yet.

        // getExternalFilesDir() and getExternalStorageDirectory() typically something app-specific like
        //   /storage/sdcard1/Android/data/com.mybackuparchives.android/files
        // so we want the great-great-grandparent folder.

        // This may be non-removable.
        Log.d(TAG, "Environment.getExternalStorageDirectory():");
        addPath(null, ancestor(Environment.getExternalStorageDirectory()), candidatePaths);

        // Context.getExternalFilesDirs() is only available from API level 19. You can use
        // ContextCompat.getExternalFilesDirs() on earlier APIs, but it only returns one dir anyway.
        Log.d(TAG, "context.getExternalFilesDir(null):");
        addPath(null, ancestor(context.getExternalFilesDir(null)), candidatePaths);

        // "Returns absolute paths to application-specific directories on all external storage
        // devices where the application can place persistent files it owns."
        // We might be able to use these to deduce a higher-level folder that isn't app-specific.
        // Also, we apparently have to call getExternalFilesDir[s](), at least in KITKAT+, in order to ensure that the
        // "external files" directory exists and is available.
        Log.d(TAG, "ContextCompat.getExternalFilesDirs(context, null):");
        addAncestors(candidatePaths, ContextCompat.getExternalFilesDirs(context, null));
        // Very similar results:
        Log.d(TAG, "ContextCompat.getExternalCacheDirs(context):");
        addAncestors(candidatePaths, ContextCompat.getExternalCacheDirs(context));

        // TODO maybe: use getExternalStorageState(File path), with and without an argument, when
        // available. With an argument is available since API level 21.
        // This may not be necessary, since we also check whether a directory exists,
        // which would fail if the external storage state is neither MOUNTED nor MOUNTED_READ_ONLY.

        // A "public" external storage directory. But in my experience it doesn't add anything helpful.
        // Note that you can't pass null, or you'll get an NPE.
        final File publicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        // Take the parent, because we tend to get a path like /pathTo/sdCard/Music.
        addPath(null, publicDirectory.getParentFile(), candidatePaths);
        // EXTERNAL_STORAGE: may not be removable.
        val = System.getenv("EXTERNAL_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);

        if (candidatePaths.isEmpty()) {
            Log.w(TAG, "No removable microSD card found.");
            return null;
        } else {
            Log.i(TAG, "\nFound potential removable storage locations: " + candidatePaths);
        }

        // Accept or eliminate candidate paths if we can determine whether they're removable storage.
        // In Lollipop and later, we can check isExternalStorageRemovable() status on each candidate.
        if (Build.VERSION.SDK_INT >= 21) {
            Iterator<File> itf = candidatePaths.iterator();
            while (itf.hasNext()) {
                File dir = itf.next();
                // handle illegalArgumentException if the path is not a valid storage device.
                try {
                    if (Environment.isExternalStorageRemovable(dir)
                        // && containsKnownFile(dir)
                            ) {
                        Log.i(TAG, dir.getPath() + " is removable external storage");
                        return dir;
                    } else if (Environment.isExternalStorageEmulated(dir)) {
                        Log.d(TAG, "Removing emulated external storage dir " + dir);
                        itf.remove();
                    }
                } catch (IllegalArgumentException e) {
                    Log.d(TAG, "isRemovable(" + dir.getPath() + "): not a valid storage device.", e);
                }
            }
        }

        // Continue trying to accept or eliminate candidate paths based on whether they're removable storage.
        // On pre-Lollipop, we only have singular externalStorage. Check whether it's removable.
        if (Build.VERSION.SDK_INT >= 9) {
            File externalStorage = Environment.getExternalStorageDirectory();
            Log.d(TAG, String.format(Locale.ROOT, "findSDCardPath: getExternalStorageDirectory = %s", externalStorage.getPath()));
            if (Environment.isExternalStorageRemovable()) {
                // Make sure this is a candidate.
                // TODO: Does this contains() work? Should we be canonicalizing paths before comparing?
                if (candidatePaths.contains(externalStorage)
                    // && containsKnownFile(externalStorage)
                        ) {
                    Log.d(TAG, "Using externalStorage dir " + externalStorage);
                    return externalStorage;
                }
            } else if (Build.VERSION.SDK_INT >= 11 && Environment.isExternalStorageEmulated()) {
                Log.d(TAG, "Removing emulated external storage dir " + externalStorage);
                candidatePaths.remove(externalStorage);
            }
        }

        // If any directory contains our special test file, consider that the microSD card.
        if (KNOWNFILE != null) {
            for (File dir : candidatePaths) {
                Log.d(TAG, String.format(Locale.ROOT, "findSdCardPath: Looking for known file in candidate path, %s", dir));
                if (containsKnownFile(dir)) return dir;
            }
        }

        // If we don't find the known file, still try taking the first candidate.
        if (!candidatePaths.isEmpty()) {
            Log.d(TAG, "No definitive path to SD card; taking the first realistic candidate.");
            return candidatePaths.iterator().next();
        }

        // If no reasonable path was found, give up.
        return null;
    }

    /** Add each path to the collection. */
    private static void addStrings(LinkedHashSet<File> candidatePaths, String[] newPaths) {
        for (String path : newPaths) {
            addPath(path, null, candidatePaths);
        }
    }

    /** Add ancestor of each File to the collection. */
    private static void addAncestors(LinkedHashSet<File> candidatePaths, File[] files) {
        for (int i = files.length - 1; i >= 0; i--) {
            addPath(null, ancestor(files[i]), candidatePaths);
        }
    }

    /**
     * Add a new candidate directory path to our list, if it's not obviously wrong.
     * Supply path as either String or File object.
     * @param strNew path of directory to add (or null)
     * @param fileNew directory to add (or null)
     */
    private static void addPath(String strNew, File fileNew, Collection<File> paths) {
        // If one of the arguments is null, fill it in from the other.
        if (strNew == null) {
            if (fileNew == null) return;
            strNew = fileNew.getPath();
        } else if (fileNew == null) {
            fileNew = new File(strNew);
        }

        if (!paths.contains(fileNew) &&
                // Check for paths known not to be removable SD card.
                // The antipattern check can be redundant, depending on where this is called from.
                !pathAntiPattern.matcher(strNew).matches()) {

            // Eliminate candidate if not a directory or not fully accessible.
            if (fileNew.exists() && fileNew.isDirectory() && fileNew.canExecute()) {
                Log.d(TAG, "  Adding candidate path " + strNew);
                paths.add(fileNew);
            } else {
                Log.d(TAG, String.format(Locale.ROOT, "  Invalid path %s: exists: %b isDir: %b canExec: %b canRead: %b",
                        strNew, fileNew.exists(), fileNew.isDirectory(), fileNew.canExecute(), fileNew.canRead()));
            }
        }
    }

    private static final String ANDROID_DIR = File.separator + "Android";

    private static File ancestor(File dir) {
        // getExternalFilesDir() and getExternalStorageDirectory() typically something app-specific like
        //   /storage/sdcard1/Android/data/com.mybackuparchives.android/files
        // so we want the great-great-grandparent folder.
        if (dir == null) {
            return null;
        } else {
            String path = dir.getAbsolutePath();
            int i = path.indexOf(ANDROID_DIR);
            if (i == -1) {
                return dir;
            } else {
                return new File(path.substring(0, i));
            }
        }
    }

    /** Returns true iff dir contains the special test file.
     * Assumes that dir exists and is a directory. (Is this a necessary assumption?) */
    private static boolean containsKnownFile(File dir) {
        if (KNOWNFILE == null) return false;

        File knownFile = new File(dir, KNOWNFILE);
        return knownFile.exists();
    }

    private static Pattern
            /** Pattern that SD card device should match */
            devicePattern = Pattern.compile("/dev/(block/.*vold.*|fuse)|/mnt/.*"),
    /** Pattern that SD card mount path should match */
    pathPattern = Pattern.compile("/(mnt|storage|external_sd|extsd|_ExternalSD|Removable|.*MicroSD).*",
            Pattern.CASE_INSENSITIVE),
    /** Pattern that the mount path should not match.
     * 'emulated' indicates an internal storage location, so skip it.
     * 'asec' is an encrypted package file, decrypted and mounted as a directory. */
    pathAntiPattern = Pattern.compile(".*(/secure|/asec|/emulated).*"),
    /** These are expected fs types, including vfat. tmpfs is not OK.
     * fuse can be removable SD card (as on Moto E or Asus ZenPad), or can be internal (Huawei G610). */
    fsTypePattern = Pattern.compile(".*(fat|msdos|ntfs|ext[34]|fuse|sdcard|esdfs).*");
}

पुनश्च

  • <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />प्रकट में मत भूलना । और एपीआई स्तर 23 और उच्चतर पर, का उपयोग सुनिश्चित करें checkSelfPermission/requestPermissions
  • KNOWNFILE = "myappfile" सेट करें यदि कोई फ़ाइल या फ़ोल्डर है जिसे आप एसडी कार्ड पर ढूंढने की उम्मीद करते हैं। यह पता लगाने और अधिक सटीक बनाता है।
  • जाहिर है आप के मूल्य को कैश करना चाहेंगे findSdCardPath(), हर बार जरूरत के समय इसे फिर से जोड़ने बजाय ।
  • Log.d()उपरोक्त कोड में लॉगिंग ( ) का एक गुच्छा है । यह ऐसे किसी भी मामले का निदान करने में मदद करता है जहां सही रास्ता नहीं मिला है। यदि आप लॉगिंग नहीं करना चाहते हैं तो इसे टिप्पणी करें।

डाउनवोटर्स, क्या आप इस उत्तर को बेहतर बनाने के लिए कोई रास्ता सुझा सकते हैं?
लार्स

1

एकमात्र समाधान जो मैंने पाया वह यह था कि प्रतिबिंब का उपयोग करता है

 /**
 * Get external sd card path using reflection
 * @param mContext
 * @param is_removable is external storage removable
 * @return
 */
private static String getExternalStoragePath(Context mContext, boolean is_removable) {

    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 result = getVolumeList.invoke(mStorageManager);
        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            Object storageVolumeElement = Array.get(result, i);
            String path = (String) getPath.invoke(storageVolumeElement);
            boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
            if (is_removable == removable) {
                return path;
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

मैं व्यक्तिगत रूप से प्रतिबिंब का उपयोग करना पसंद नहीं करता क्योंकि Google Android के नए संस्करणों में पिछड़े संगतता की सराहना नहीं करता है!
बेहरोज

0

मुझे पता नहीं क्यों लेकिन मुझे इसे उपयोग करने से पहले सार्वजनिक भंडारण निर्देशिकाओं में बनाई गई फ़ाइल पर .createNewFile () कॉल करने की आवश्यकता है। उस पद्धति के लिए टिप्पणियों में कहा गया है कि यह उपयोगी नहीं है। यहाँ एक नमूना है ...


 String myPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS) + File.separator + "My Directory";
            final File myDir = new File(myPath);
            try {
                myDir.mkdirs();
            } catch (Exception ex) {
                Toast.makeText(this, "error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
            }

        String fname = "whatever";
        File newFile = new File(myDir, fname);

        Log.i(TAG, "File exists --> " + newFile.exists()) //will be false  
    try {
            if (newFile.createNewFile()) {

                 //continue 

              } else {

                Log.e(TAG, "error creating file");

            }

        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }


0

मैंने डिवाइस पर एसडी कार्ड उपलब्ध है या नहीं, यह जांचने के लिए एक बर्तन विधि बनाई है और यदि यह उपलब्ध हो तो डिवाइस पर एसडी कार्ड पथ प्राप्त करें।

आप अपनी परियोजना के वर्ग में 2 विधियों की प्रतिलिपि बना सकते हैं जिनकी आपको आवश्यकता है। बस इतना ही।

public String isRemovableSDCardAvailable() {
    final String FLAG = "mnt";
    final String SECONDARY_STORAGE = System.getenv("SECONDARY_STORAGE");
    final String EXTERNAL_STORAGE_DOCOMO = System.getenv("EXTERNAL_STORAGE_DOCOMO");
    final String EXTERNAL_SDCARD_STORAGE = System.getenv("EXTERNAL_SDCARD_STORAGE");
    final String EXTERNAL_SD_STORAGE = System.getenv("EXTERNAL_SD_STORAGE");
    final String EXTERNAL_STORAGE = System.getenv("EXTERNAL_STORAGE");

    Map<Integer, String> listEnvironmentVariableStoreSDCardRootDirectory = new HashMap<Integer, String>();
    listEnvironmentVariableStoreSDCardRootDirectory.put(0, SECONDARY_STORAGE);
    listEnvironmentVariableStoreSDCardRootDirectory.put(1, EXTERNAL_STORAGE_DOCOMO);
    listEnvironmentVariableStoreSDCardRootDirectory.put(2, EXTERNAL_SDCARD_STORAGE);
    listEnvironmentVariableStoreSDCardRootDirectory.put(3, EXTERNAL_SD_STORAGE);
    listEnvironmentVariableStoreSDCardRootDirectory.put(4, EXTERNAL_STORAGE);

    File externalStorageList[] = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        externalStorageList = getContext().getExternalFilesDirs(null);
    }
    String directory = null;
    int size = listEnvironmentVariableStoreSDCardRootDirectory.size();
    for (int i = 0; i < size; i++) {
        if (externalStorageList != null && externalStorageList.length > 1 && externalStorageList[1] != null)
            directory = externalStorageList[1].getAbsolutePath();
        else
            directory = listEnvironmentVariableStoreSDCardRootDirectory.get(i);

        directory = canCreateFile(directory);
        if (directory != null && directory.length() != 0) {
            if (i == size - 1) {
                if (directory.contains(FLAG)) {
                    Log.e(getClass().getSimpleName(), "SD Card's directory: " + directory);
                    return directory;
                } else {
                    return null;
                }
            }
            Log.e(getClass().getSimpleName(), "SD Card's directory: " + directory);
            return directory;
        }
    }
    return null;
}

/**
 * Check if can create file on given directory. Use this enclose with method
 * {@link BeginScreenFragement#isRemovableSDCardAvailable()} to check sd
 * card is available on device or not.
 * 
 * @param directory
 * @return
 */
public String canCreateFile(String directory) {
    final String FILE_DIR = directory + File.separator + "hoang.txt";
    File tempFlie = null;
    try {
        tempFlie = new File(FILE_DIR);
        FileOutputStream fos = new FileOutputStream(tempFlie);
        fos.write(new byte[1024]);
        fos.flush();
        fos.close();
        Log.e(getClass().getSimpleName(), "Can write file on this directory: " + FILE_DIR);
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Write file error: " + e.getMessage());
        return null;
    } finally {
        if (tempFlie != null && tempFlie.exists() && tempFlie.isFile()) {
            // tempFlie.delete();
            tempFlie = null;
        }
    }
    return directory;
}

-1

सभी बाहरी उपकरणों के लिए इसका काम है, लेकिन सुनिश्चित करें कि केवल बाहरी डिवाइस फ़ोल्डर नाम प्राप्त करें और फिर आपको फ़ाइल वर्ग का उपयोग करके दिए गए स्थान से फ़ाइल प्राप्त करने की आवश्यकता है।

public static List<String> getExternalMounts() {
        final List<String> out = new ArrayList<>();
        String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
        String s = "";
        try {
            final Process process = new ProcessBuilder().command("mount")
                    .redirectErrorStream(true).start();
            process.waitFor();
            final InputStream is = process.getInputStream();
            final byte[] buffer = new byte[1024];
            while (is.read(buffer) != -1) {
                s = s + new String(buffer);
            }
            is.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }

        // parse output
        final String[] lines = s.split("\n");
        for (String line : lines) {
            if (!line.toLowerCase(Locale.US).contains("asec")) {
                if (line.matches(reg)) {
                    String[] parts = line.split(" ");
                    for (String part : parts) {
                        if (part.startsWith("/"))
                            if (!part.toLowerCase(Locale.US).contains("vold"))
                                out.add(part);
                    }
                }
            }
        }
        return out;
    }

कॉलिंग:

List<String> list=getExternalMounts();
        if(list.size()>0)
        {
            String[] arr=list.get(0).split("/");
            int size=0;
            if(arr!=null && arr.length>0) {
                size= arr.length - 1;
            }
            File parentDir=new File("/storage/"+arr[size]);
            if(parentDir.listFiles()!=null){
                File parent[] = parentDir.listFiles();

                for (int i = 0; i < parent.length; i++) {

                    // get file path as parent[i].getAbsolutePath());

                }
            }
        }

बाहरी संग्रहण तक पहुँच प्राप्त करना

बाह्य संग्रहण पर फ़ाइलों को पढ़ने या लिखने के लिए, आपके ऐप को READ_EXTERNAL_STORAGE या WRITE_EXTERNAL_STORAGE सिस्टम अनुमतियां प्राप्त करनी होंगी । उदाहरण के लिए:

<manifest ...>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    ...
</manifest>

-2

/ sdcard => इंटरनल स्टोरेज (यह एक सिमलिंक है लेकिन काम करना चाहिए)

/ mnt / extSdCard => बाहरी एसडीकार्ड

यह सैमसंग गैलेक्सी एस 3 के लिए है

तुम शायद इस पर बैंक कर सकते हो सच के लिए सबसे ... दोहरी जाँच फिर भी!


8
मेरे पास कई अलग-अलग एंड्रॉइड फोन हैं, उनमें से लगभग आधे सैमसंग हैं, और कभी भी इस स्थान का उपयोग नहीं देखा है। यह S3 पर सही हो सकता है, लेकिन यह कहना कि "आप शायद इस पर बैंक बना सकते हैं कि ज्यादातर के लिए सच है" पूरी तरह से गलत है।
जोबिट्स 15'13

गलत। /sdcardमेरी सोनी 2305 पर बाहरी के लिए एक सहानुभूति है।
जिगगंज

2
क्या मैंने यह नहीं कहा कि यह नहीं हो सकता है?
रोबिनकोनोर
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.