Example usage for android.content Context CONTEXT_IGNORE_SECURITY

List of usage examples for android.content Context CONTEXT_IGNORE_SECURITY

Introduction

In this page you can find the example usage for android.content Context CONTEXT_IGNORE_SECURITY.

Prototype

int CONTEXT_IGNORE_SECURITY

To view the source code for android.content Context CONTEXT_IGNORE_SECURITY.

Click Source Link

Document

Flag for use with #createPackageContext : ignore any security restrictions on the Context being requested, allowing it to always be loaded.

Usage

From source file:com.gnuroot.debian.GNURootMain.java

private void copyAssets(String packageName) {
    Context friendContext = null;
    try {/* w  w w .ja  va  2s.  co m*/
        friendContext = this.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
    } catch (NameNotFoundException e1) {
        return;
    }
    AssetManager assetManager = friendContext.getAssets();
    File tempFile = new File(getInstallDir().getAbsolutePath() + "/support");
    if (!tempFile.exists()) {
        tempFile.mkdir();
    }
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(filename);
            filename = filename.replace(".mp2", "");
            filename = filename.replace(".mp3", ".tar.gz");
            File outFile = new File(tempFile, filename);
            out = new FileOutputStream(outFile);
            if (filename.contains(".tar.gz"))
                out = openFileOutput(filename, MODE_PRIVATE);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
            exec("chmod 0777 " + outFile.getAbsolutePath(), true);
        } catch (IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }
    }
}

From source file:com.aware.Aware.java

/**
 * Given a plugin's package name, fetch the context card for reuse.
 * @param context: application context/*  w  ww. j a  v a 2 s . co m*/
 * @param package_name: plugin's package name
 * @return View for reuse (instance of LinearLayout)
 */
public static View getContextCard(final Context context, final String package_name) {

    if (!isClassAvailable(context, package_name, "ContextCard")) {
        return null;
    }

    String ui_class = package_name + ".ContextCard";
    LinearLayout card = new LinearLayout(context);
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    card.setLayoutParams(params);
    card.setOrientation(LinearLayout.VERTICAL);

    try {
        Context packageContext = context.createPackageContext(package_name,
                Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);

        Class<?> fragment_loader = packageContext.getClassLoader().loadClass(ui_class);
        Object fragment = fragment_loader.newInstance();
        Method[] allMethods = fragment_loader.getDeclaredMethods();
        Method m = null;
        for (Method mItem : allMethods) {
            String mName = mItem.getName();
            if (mName.contains("getContextCard")) {
                mItem.setAccessible(true);
                m = mItem;
                break;
            }
        }

        View ui = (View) m.invoke(fragment, packageContext);
        if (ui != null) {
            //Check if plugin has settings. If it does, tapping the card shows the settings
            if (isClassAvailable(context, package_name, "Settings")) {
                ui.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent open_settings = new Intent();
                        open_settings.setClassName(package_name, package_name + ".Settings");
                        open_settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(open_settings);
                    }
                });
            }

            //Set card look-n-feel
            ui.setBackgroundColor(Color.WHITE);
            ui.setPadding(20, 20, 20, 20);
            card.addView(ui);

            LinearLayout shadow = new LinearLayout(context);
            LayoutParams params_shadow = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            params_shadow.setMargins(0, 0, 0, 10);
            shadow.setBackgroundColor(context.getResources().getColor(R.color.card_shadow));
            shadow.setMinimumHeight(5);
            shadow.setLayoutParams(params_shadow);
            card.addView(shadow);

            return card;
        } else {
            return null;
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.aware.Aware.java

/**
* Given a package and class name, check if the class exists or not.
* @param package_name//ww  w  .ja v  a  2  s.co  m
* @param class_name
* @return true if exists, false otherwise
*/
private static boolean isClassAvailable(Context context, String package_name, String class_name) {
    try {
        Context package_context = context.createPackageContext(package_name,
                Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
        package_context.getClassLoader().loadClass(package_name + "." + class_name);
    } catch (ClassNotFoundException e) {
        return false;
    } catch (NameNotFoundException e) {
        return false;
    }
    return true;
}

From source file:me.piebridge.bible.Bible.java

private void checkApkData() {
    Log.d(TAG, "checking apkdata");
    try {//from   ww  w .  j a v a 2s. co  m
        String packageName = mContext.getPackageName();
        PackageManager pm = mContext.getPackageManager();
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(mContext);
        ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
        for (String applicationName : pm.getPackagesForUid(ai.uid)) {
            if (packageName.equals(applicationName)) {
                continue;
            }

            // version
            String version = applicationName.replace(packageName + ".", "");

            // resources
            Resources resources = mContext
                    .createPackageContext(applicationName, Context.CONTEXT_IGNORE_SECURITY).getResources();

            // newVersion
            int versionCode = pm.getPackageInfo(applicationName, 0).versionCode;
            boolean newVersion = (preference.getInt(version, 0) != versionCode);

            // resid
            int resid = resources.getIdentifier("a", "raw", applicationName);
            if (resid == 0) {
                resid = resources.getIdentifier("xa", "raw", applicationName);
            }
            if (resid == 0) {
                Log.d(TAG, "package " + applicationName + " has no R.raw.a nor R.raw.xa");
                continue;
            }

            // file
            File file;
            if (versionpaths.containsKey(version)) {
                file = new File(versionpaths.get(version));
            } else {
                file = new File(getExternalFilesDirWrapper(), version + ".sqlite3");
            }
            if (file.exists() && !file.isFile()) {
                file.delete();
            }

            boolean unpack = unpackRaw(resources, newVersion, resid, file);
            if (newVersion && unpack) {
                preference.edit().putInt(version, versionCode).commit();
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "", e);
    }
}

From source file:com.landenlabs.all_devtool.PackageFragment.java

/**
 * Delete cache files.// w  w  w . j av  a 2 s  .  c om
 */
private void deleteCaches() {
    ArrayList<PackageInfo> uninstallList = new ArrayList<PackageInfo>();
    for (PackingItem packageItem : m_list) {
        if (packageItem.m_checked) {

            try {
                PackageInfo packInfo = packageItem.m_packInfo;
                long cacheSize = 0;
                long fileCount = 0;
                Context mContext = getActivity().createPackageContext(packInfo.packageName,
                        Context.CONTEXT_IGNORE_SECURITY);

                File cacheDirectory = null;
                Utils.DirSizeCount cacheDirSize = null;
                if (mContext.getCacheDir() != null) {
                    cacheDirectory = mContext.getCacheDir();
                    // cacheSize = cacheDirectory.length()/1024;
                    cacheDirSize = Utils.getDirectorySize(cacheDirectory);
                    if (cacheDirSize == null) {
                        // Cache is not readable or empty,
                        // Try and map cache dir to one of the sd storage paths
                        for (String storageDir : m_storageDirs) {
                            try {
                                File cacheDirectory2 = new File(cacheDirectory.getCanonicalPath()
                                        .replace("/data/data", storageDir + "/Android/data"));
                                if (cacheDirectory2.exists()) {
                                    cacheDirectory = cacheDirectory2;
                                    cacheDirSize = Utils.getDirectorySize(cacheDirectory);
                                    break;
                                }
                            } catch (Exception ex) {
                                m_log.d(ex.getMessage());
                            }
                        }
                    }

                    if (cacheDirSize != null) {
                        List<String> deletedFiles = Utils.deleteFiles(cacheDirectory);
                        if (deletedFiles == null || deletedFiles.isEmpty()) {

                        } else {
                            String fileMsg = TextUtils.join("\n", deletedFiles.toArray());
                            Toast.makeText(getContext(), packageItem.m_appName + "\n" + fileMsg,
                                    Toast.LENGTH_LONG).show();

                        }
                    }
                }
            } catch (Exception ex) {
                m_log.e(ex.getLocalizedMessage());
            }
        }
    }

    // ((BaseExpandableListAdapter) m_listView.getExpandableListAdapter()).notifyDataSetChanged();
    // updateList();
    loadPackages();
}

From source file:org.mozilla.gecko.GeckoAppShell.java

public static Class<?> loadPluginClass(String className, String libName) {
    Log.i(LOGTAG, "in loadPluginClass... attempting to access className, then libName.....");
    Log.i(LOGTAG, "className: " + className);
    Log.i(LOGTAG, "libName: " + libName);

    try {// ww  w. java2s . c  om
        String packageName = GeckoApp.mAppContext.getPluginPackage(libName);
        Log.i(LOGTAG, "load \"" + className + "\" from \"" + packageName + "\" for \"" + libName + "\"");
        Context pluginContext = GeckoApp.mAppContext.createPackageContext(packageName,
                Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
        ClassLoader pluginCL = pluginContext.getClassLoader();
        return pluginCL.loadClass(className);
    } catch (ClassNotFoundException cnfe) {
        Log.i(LOGTAG, "class not found", cnfe);
    } catch (PackageManager.NameNotFoundException nnfe) {
        Log.i(LOGTAG, "package not found", nnfe);
    }
    Log.e(LOGTAG, "couldn't find class");
    return null;
}

From source file:com.landenlabs.all_devtool.PackageFragment.java

/**
 * Load installed (user or system) packages.
 *
 * TODO - include//from  w w  w  . j  a  v  a 2s.c om
 *    /data/local/tmp
 *    /sdcard/local/tmp ?
 *    /storage/sdcardx/LOST.DIR/
 *    /sdcard/download
 *
 */
void loadCachedPackages() {
    try {
        // m_pkgUninstallBtn.setText(R.string.package_uninstall);
        m_uninstallResId = R.string.package_del_cache;
        m_pkgUninstallBtn.post(new Runnable() {
            @Override
            public void run() {
                updateUninstallBtn();
            }
        });

        m_workList = new ArrayList<PackingItem>();

        // PackageManager.GET_SIGNATURES | PackageManager.GET_PERMISSIONS | PackageManager.GET_PROVIDERS;
        int flags1 = PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES
                | PackageManager.GET_INTENT_FILTERS;
        int flags2 = PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES;
        int flags3 = PackageManager.GET_META_DATA;
        int flags4 = 0;

        List<PackageInfo> packList = getActivity().getPackageManager().getInstalledPackages(flags1);
        /*
        packList = mergePackages(packList,
            getActivity().getPackageManager().getInstalledPackages(flags2));
        packList = mergePackages(packList,
            getActivity().getPackageManager().getInstalledPackages(flags3));
        packList = mergePackages(packList,
            getActivity().getPackageManager().getInstalledPackages(flags4));
        */

        if (packList != null)
            for (int idx = 0; idx < packList.size(); idx++) {
                PackageInfo packInfo = packList.get(idx);
                long cacheSize = 0;
                long fileCount = 0;

                if (packInfo == null || packInfo.lastUpdateTime <= 0) {
                    continue; // Bad package
                }

                Context pkgContext;
                try {
                    m_log.d(String.format("%3d/%d : %s", idx, packList.size(), packInfo.packageName));
                    pkgContext = getActivity().createPackageContext(packInfo.packageName,
                            Context.CONTEXT_IGNORE_SECURITY);
                } catch (Exception ex) {
                    m_log.e(ex.getLocalizedMessage());
                    continue; // Bad package
                }

                File cacheDirectory = null;
                Utils.DirSizeCount cacheDirSize = null;
                if (pkgContext.getCacheDir() != null) {
                    cacheDirectory = pkgContext.getCacheDir();
                } else {
                    // cacheDirectory = new File(mContext.getPackageResourcePath());
                    if (pkgContext.getFilesDir() != null) {
                        String dataPath = pkgContext.getFilesDir().getPath(); // "/data/data/"
                        cacheDirectory = new File(dataPath, pkgContext.getPackageName() + "/cache");
                    }
                }

                if (cacheDirectory != null) {
                    // cacheSize = cacheDirectory.length()/1024;
                    cacheDirSize = Utils.getDirectorySize(cacheDirectory);
                    if (true) {
                        // Cache is not readable or empty,
                        // Try and map cache dir to one of the sd storage paths
                        for (String storageDir : m_storageDirs) {
                            try {
                                File cacheDirectory2 = new File(cacheDirectory.getCanonicalPath()
                                        .replace("/data/data", storageDir + "/Android/data"));
                                if (cacheDirectory2.exists()) {
                                    cacheDirectory = cacheDirectory2;
                                    Utils.DirSizeCount dirSize = Utils.getDirectorySize(cacheDirectory2);
                                    if (cacheDirSize == null || dirSize.size > cacheDirSize.size) {
                                        cacheDirSize = dirSize;
                                        cacheDirectory = cacheDirectory2;
                                    }
                                }
                            } catch (Exception ex) {
                                m_log.d(ex.getMessage());
                            }
                        }
                    }
                } else {
                    m_log.d(packInfo.packageName + " missing cache dir");
                }

                Utils.DirSizeCount datDirSize = null;
                if (packInfo.applicationInfo.dataDir != null) {
                    try {
                        datDirSize = Utils.getDirectorySize(new File(packInfo.applicationInfo.dataDir));
                    } catch (Exception ex) {

                    }
                }

                /*
                                    Method getPackageSizeInfo;
                                    try {
                getPackageSizeInfo = getActivity().getPackageManager().getClass().getMethod(
                        "getPackageSizeInfo", String.class,
                        Class.forName("android.content.pm.IPackageStatsObserver"));
                        
                getPackageSizeInfo.invoke(getActivity().getPackageManager(), packInfo.packageName,
                        new IPackageStatsObserver() {
                        
                            @Override
                            public void onGetStatsCompleted(
                                    PackageStats pStats, boolean succeeded)
                                    throws RemoteException {
                        
                                totalSize = totalSize + pStats.cacheSize;
                            }
                        }
                );
                                    } catch (Exception e) {
                continue;
                                    }
                */
                /* if ((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) */ {
                    ArrayListPairString pkgList = new ArrayListPairString();
                    String appName = "unknown";
                    try {
                        appName = packInfo.applicationInfo.loadLabel(getActivity().getPackageManager())
                                .toString().trim();
                    } catch (Exception ex) {
                        m_log.e(ex.getLocalizedMessage());
                    }
                    long pkgSize = 0;

                    addList(pkgList, "Version", packInfo.versionName);
                    addList(pkgList, "TargetSDK", String.valueOf(packInfo.applicationInfo.targetSdkVersion));
                    String installTyp = "auto";
                    if (Build.VERSION.SDK_INT >= 21) {
                        switch (packInfo.installLocation) {
                        case PackageInfo.INSTALL_LOCATION_AUTO:
                            break;
                        case PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY:
                            installTyp = "internal";
                            break;
                        case PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL:
                            installTyp = "external";
                            break;
                        }
                    }
                    addList(pkgList, "Install", installTyp);

                    // Add application info.
                    try {
                        addList(pkgList, "Allow Backup",
                                String.valueOf((packInfo.applicationInfo.flags & FLAG_ALLOW_BACKUP) != 0));
                        addList(pkgList, "Debuggable", String.valueOf(
                                (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0));
                        addList(pkgList, "External Storage", String.valueOf(
                                (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0));
                        String themeName = getResourceName(packInfo, packInfo.applicationInfo.theme);
                        if (!TextUtils.isEmpty(themeName))
                            addList(pkgList, "Theme", themeName);
                    } catch (Exception ex) {
                        Log.d("foo", ex.getMessage());
                    }

                    try {
                        File file = new File(packInfo.applicationInfo.sourceDir);
                        pkgSize = file.length();
                    } catch (Exception ex) {
                    }

                    addList(pkgList, "Apk File", packInfo.applicationInfo.publicSourceDir);
                    addList(pkgList, "Apk Size",
                            NumberFormat.getNumberInstance(Locale.getDefault()).format(pkgSize));

                    addList(pkgList, "Src Dir", packInfo.applicationInfo.sourceDir);
                    addList(pkgList, "lib Dir", packInfo.applicationInfo.nativeLibraryDir);

                    addList(pkgList, "dat Dir", packInfo.applicationInfo.dataDir);
                    if (null != datDirSize) {
                        addList(pkgList, "*  Dir Size",
                                NumberFormat.getNumberInstance(Locale.getDefault()).format(datDirSize.size));
                        addList(pkgList, "*  File Count",
                                NumberFormat.getNumberInstance(Locale.getDefault()).format(datDirSize.count));
                    }

                    if (null != cacheDirectory) {
                        addList(pkgList, "Cache", cacheDirectory.getCanonicalPath());
                        if (null != cacheDirSize) {
                            cacheSize = cacheDirSize.size;
                            addList(pkgList, "*  Dir Size", NumberFormat.getNumberInstance(Locale.getDefault())
                                    .format(cacheDirSize.size));
                            addList(pkgList, "*  File Count", NumberFormat
                                    .getNumberInstance(Locale.getDefault()).format(cacheDirSize.count));
                        }
                    }

                    if (null != packInfo.applicationInfo.sharedLibraryFiles
                            && packInfo.applicationInfo.sharedLibraryFiles.length != 0) {
                        addList(pkgList, "ShareLibs", NumberFormat.getNumberInstance(Locale.getDefault())
                                .format(packInfo.applicationInfo.sharedLibraryFiles.length));
                        for (String shrLibStr : packInfo.applicationInfo.sharedLibraryFiles) {
                            addList(pkgList, "  ", shrLibStr);
                        }
                    }

                    if (true) {
                        // packInfo.configPreferences; use with flag= GET_CONFIGURATIONS;
                        // packInfo.providers use with GET_PROVIDERS;

                        List<IntentFilter> outFilters = new ArrayList<IntentFilter>();
                        List<ComponentName> outActivities = new ArrayList<ComponentName>();
                        int num = getActivity().getPackageManager().getPreferredActivities(outFilters,
                                outActivities, packInfo.packageName);
                        if (num > 0) {
                            addList(pkgList, "Preferred #", String.valueOf(num));
                        }
                    }

                    /* if (null != cacheDirectory) */
                    // if (cacheDirSize != null)
                    {
                        m_workList.add(new PackingItem(packInfo.packageName.trim(), pkgList, packInfo,
                                cacheSize, appName));
                    }
                }
            }

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:com.android.mms.ui.MessageUtils.java

public static void setMmsLimitSize(Context context) {
    Context otherAppContext = null;
    SharedPreferences sp = null;//from   www. j  av  a  2s. c o m
    try {
        otherAppContext = context.createPackageContext("com.android.mms", Context.CONTEXT_IGNORE_SECURITY);

    } catch (Exception e) {
        MmsLog.e(TAG, "ConversationList NotFoundContext");
    }
    if (otherAppContext != null) {
        sp = otherAppContext.getSharedPreferences("com.android.mms_preferences", Context.MODE_PRIVATE);
    }
    String mSizeLimitTemp = null;
    int mMmsSizeLimit = 0;
    if (sp != null) {
        //Modify JWYYL-1510 chenshu 20150121 start-->
        //mSizeLimitTemp = sp.getString("pref_key_mms_size_limit", "300");
        if (context.getResources().getBoolean(R.bool.support_MMS_max_size_limit)) {
            mSizeLimitTemp = sp.getString("pref_key_mms_size_limit",
                    String.valueOf(context.getResources().getInteger(R.integer.mms_custom_size)));
        } else {
            mSizeLimitTemp = sp.getString("pref_key_mms_size_limit", "300");
        }
        //Modify JWYYL-1510 chenshu 20150121 end-->
    }
    if (mSizeLimitTemp != null && 0 == mSizeLimitTemp.compareTo("100")) {
        mMmsSizeLimit = 100;
    } else if (mSizeLimitTemp != null && 0 == mSizeLimitTemp.compareTo("200")) {
        mMmsSizeLimit = 200;
        //Add JWYYL-1510 chenshu 20150121 start-->
    } else if (mSizeLimitTemp != null && 0 == mSizeLimitTemp.compareTo("600")) {
        mMmsSizeLimit = 600;
    } else if (mSizeLimitTemp != null && 0 == mSizeLimitTemp.compareTo("900")) {
        mMmsSizeLimit = 900;
    } else if (mSizeLimitTemp != null && 0 == mSizeLimitTemp.compareTo("1024")) {
        mMmsSizeLimit = 1024;
        //Add JWYYL-1510 chenshu 20150121 end-->
    } else {
        //Modify JWYYL-1510 chenshu 20150121 start-->
        //mMmsSizeLimit = 300;
        if (context.getResources().getBoolean(R.bool.support_MMS_max_size_limit)) {
            mMmsSizeLimit = context.getResources().getInteger(R.integer.mms_custom_size);
            MmsLog.e("chenshu", "mMmsSizeLimit:" + mMmsSizeLimit);
        } else {
            mMmsSizeLimit = 300;
        }
        //Modify JWYYL-1510 chenshu 20150121 end-->
    }

    MmsLog.e("chenshu", "mMmsSizeLimit:" + mMmsSizeLimit);
    MmsConfig.setUserSetMmsSizeLimit(mMmsSizeLimit);
}