2011-04-28 74 views
5

上我想的東西做這樣的事情:我如何才能知道我的應用程序安裝SD卡

val cacheDir = if (installedOnSD) 
    { 
    getContext.getExternalCacheDir 
    } 
else 
    { 
    getContext.getCacheDir 
    } 

,我在爲installedOnSD部分損失感到有點。任何人都可以指出我正確的方向嗎?

PS:Scala中的僞代碼示例,僅供參考。

回答

9

這裏是我的,如果安裝在SD卡上的應用程序檢查代碼:

/** 
    * Checks if the application is installed on the SD card. 
    * 
    * @return <code>true</code> if the application is installed on the sd card 
    */ 
    public static boolean isInstalledOnSdCard() { 

    Context context = App.getContext(); 
    // check for API level 8 and higher 
    if (VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) { 
     PackageManager pm = context.getPackageManager(); 
     try { 
     PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); 
     ApplicationInfo ai = pi.applicationInfo; 
     return (ai.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE; 
     } catch (NameNotFoundException e) { 
     // ignore 
     } 
    } 

    // check for API level 7 - check files dir 
    try { 
     String filesDir = context.getFilesDir().getAbsolutePath(); 
     if (filesDir.startsWith("/data/")) { 
     return false; 
     } else if (filesDir.contains("/mnt/") || filesDir.contains("/sdcard/")) { 
     return true; 
     } 
    } catch (Throwable e) { 
     // ignore 
    } 

    return false; 
    } 
+0

有趣。我認爲API級別7適用於固定電話。而進口缺失。 – Martin 2011-06-22 07:34:21

1

來檢查應用程序安裝在SD卡或沒有,只是這樣做:

ApplicationInfo io = context.getApplicationInfo(); 

if(io.sourceDir.startsWith("/data/")) { 

//application is installed in internal memory 
return false; 

} else if(io.sourceDir.startsWith("/mnt/") || io.sourceDir.startsWith("/sdcard/")) { 

//application is installed in sdcard(external memory) 
return true; 
} 
相關問題