Android 2.2 - How do I detect if I am installed on the SDCard or not?

旧巷老猫 提交于 2019-12-03 12:25:41
Charlie Collins

You could use PackageManager to get the ApplicationInfo, and from there check the "flags" for FLAG_EXTERNAL_STORAGE.

Here's a quick example I made to demonstrate:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PackageManager pm = getPackageManager();
    try {
       PackageInfo pi = pm.getPackageInfo("com.totsp.helloworld", 0);
       ApplicationInfo ai = pi.applicationInfo;
       // this only works on API level 8 and higher (check that first)
       Toast
                .makeText(
                         this,
                         "Value of FLAG_EXTERNAL_STORAGE:"
                                  + ((ai.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE),
                         Toast.LENGTH_LONG).show();
    } catch (NameNotFoundException e) {
       // do something
    }
}

Still, depending on your situation (whether or not you have all the "media" up front, or the user gets/creates it as they use the app), you may want to put it on the external storage regardless. A large size internal app is frowned upon by many users (and a lot of internal media would probably make it huge).

peceps

Here is my code for checking if app is installed on SD card:

  /**
   * 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 = MbridgeApp.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;
  }

To Check application is installed in SD Card or not, just do this:

ApplicationInfo io = context.getApplicationInfo();

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

//application is installed in internal memory

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

//application is installed in sdcard(external memory)

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!