Example usage for android.content Context createPackageContext

List of usage examples for android.content Context createPackageContext

Introduction

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

Prototype

public abstract Context createPackageContext(String packageName, @CreatePackageOptions int flags)
        throws PackageManager.NameNotFoundException;

Source Link

Document

Return a new Context object for the given application name.

Usage

From source file:com.github.michalbednarski.intentslab.browser.ComponentInfoFragment.java

public static CharSequence dumpMetaData(final Context context, final String packageName, Bundle metaData) {
    FormattedTextBuilder text = new FormattedTextBuilder();
    Context foreignContext = null;
    try {//ww w.  j a v a  2 s.  co  m
        foreignContext = context.createPackageContext(packageName, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    if (metaData != null && !metaData.isEmpty()) {
        text.appendHeader(context.getString(R.string.metadata_header));
        for (String key : metaData.keySet()) {
            Object value = metaData.get(key);
            if (value instanceof Integer) {
                // TODO resource?
                if (foreignContext != null) {
                    text.appendValueNoNewLine(key, value.toString());
                    // Integers can point to resources
                    final int resId = (Integer) value;
                    if (resId == 0) {
                        continue;
                    }

                    // [View as XML] link
                    try {
                        foreignContext.getResources().getXml(resId);
                        text.appendClickable(context.getString(R.string.view_as_xml_resource),
                                new ClickableSpan() {
                                    @Override
                                    public void onClick(View widget) {
                                        context.startActivity(new Intent(context, SingleFragmentActivity.class)
                                                .putExtra(SingleFragmentActivity.EXTRA_FRAGMENT,
                                                        XmlViewerFragment.class.getName())
                                                .putExtra(XmlViewerFragment.ARG_PACKAGE_NAME, packageName)
                                                .putExtra(XmlViewerFragment.ARG_RESOURCE_ID, resId));
                                    }
                                });
                    } catch (Resources.NotFoundException ignored) {
                    }
                }
                // Other types
            } else if (value instanceof Float) {
                text.appendValueNoNewLine(key,
                        value.toString() + (((Float) value) % 1f == 0f ? "" : " (float)"));
            } else if (value instanceof Boolean) {
                text.appendValueNoNewLine(key, value.toString());
            } else if (value instanceof String) {
                text.appendValueNoNewLine(key, "\"" + value + "\"");
            }
        }
    }
    return text.getText();
}

From source file:at.tugraz.iaik.magnum.conf.Preferences.java

private Preferences(Context ctx) {
    this.ctx = ctx;
    try {/*  www  .  j  av a2 s  . co m*/
        prefs = ctx.createPackageContext(Constants.MAGNUM_CONTEXT, Context.MODE_PRIVATE)
                .getSharedPreferences(HOOKED_PACKAGES, Context.MODE_PRIVATE);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        prefs = null;
    }
    Log.d("PREF", prefs == null ? "null" : prefs.toString());
    packageConfig = getPackageSettings();
}

From source file:com.germainz.identiconizer.xposed.XposedMod.java

@Override
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
    if ("com.android.providers.contacts".equals(lpparam.packageName)) {
        try {//from w  w w .  java2  s. c o m
            findAndHookMethod("com.android.providers.contacts.DataRowHandlerForStructuredName",
                    lpparam.classLoader, "insert", SQLiteDatabase.class,
                    "com.android.providers.contacts.TransactionContext", long.class, ContentValues.class,
                    new XC_MethodHook() {

                        @Override
                        protected void beforeHookedMethod(XC_MethodHook.MethodHookParam param)
                                throws Throwable {
                            CONFIG.reload();
                            if (CONFIG.isEnabled()) {
                                ContentValues values = (ContentValues) param.args[3];
                                String name = values.getAsString(
                                        ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);

                                if (!TextUtils.isEmpty(name)) {
                                    long rawContactId = ((Number) param.args[2]).longValue();
                                    SQLiteDatabase db = (SQLiteDatabase) param.args[0];
                                    Identicon identicon = IdenticonFactory.makeIdenticon(
                                            CONFIG.getIdenticonStyle(), CONFIG.getIdenticonSize(),
                                            CONFIG.getIdenticonBgColor());

                                    ContentValues identiconValues = new ContentValues();
                                    identiconValues.put("mimetype_id", 10);
                                    identiconValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
                                    identiconValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO,
                                            identicon.generateIdenticonByteArray(name));
                                    identiconValues.put(ContactsContract.Data.IS_PRIMARY, 1);
                                    identiconValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);

                                    db.insert(ContactsContract.Contacts.Data.CONTENT_DIRECTORY, null,
                                            identiconValues);
                                }
                            }
                        }
                    });
        } catch (Throwable e) {
            Context systemContext = (Context) getStaticObjectField(
                    findClass("android.app.ActivityThread", null), "mSystemContext");
            if (systemContext == null) {
                Object activityThread = callStaticMethod(findClass("android.app.ActivityThread", null),
                        "currentActivityThread");
                systemContext = (Context) callMethod(activityThread, "getSystemContext");
            }

            Context contactsProviderContext = systemContext
                    .createPackageContext("com.android.providers.contacts", Context.CONTEXT_IGNORE_SECURITY);
            Context identiconizerContext = systemContext.createPackageContext(Config.PACKAGE_NAME,
                    Context.CONTEXT_IGNORE_SECURITY);

            String contentText = identiconizerContext.getString(R.string.xposed_error_text);
            Notification notice = new NotificationCompat.Builder(contactsProviderContext)
                    .setSmallIcon(NOTIF_ICON_RES_ID)
                    .setContentTitle(identiconizerContext.getString(R.string.xposed_error_title))
                    .setContentText(contentText)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(contentText)).build();
            NotificationManager nm = (NotificationManager) contactsProviderContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            nm.notify(1, notice);
        }
    }

    if (Config.PACKAGE_NAME.equals(lpparam.packageName)) {
        findAndHookMethod(Config.PACKAGE_NAME + ".Config", lpparam.classLoader, "isXposedModActive",
                XC_MethodReplacement.returnConstant(true));
    }
}

From source file:com.aware.Aware.java

/**
* Given a package and class name, check if the class exists or not.
* @param package_name/*from   ww w.j  av  a2 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:com.aware.Aware.java

/**
 * Given a plugin's package name, fetch the context card for reuse.
 * @param context: application context/*from ww w . j  a  v  a2 s . c om*/
 * @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.android.mms.ui.MessageUtils.java

public static void setMmsLimitSize(Context context) {
    Context otherAppContext = null;
    SharedPreferences sp = null;//from w  w  w.j a v  a 2  s.com
    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);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String GetAppRoot(String AppName) {
    String sRet = sErrorPrefix + " internal error [no context]";
    Context ctx = contextWrapper.getApplicationContext();

    if (ctx != null) {
        try {//from  w  w  w  . ja v a  2  s  .  c o  m
            Context appCtx = ctx.createPackageContext(AppName, 0);
            ContextWrapper appCtxW = new ContextWrapper(appCtx);
            sRet = appCtxW.getApplicationInfo().dataDir;
            appCtxW = null;
            appCtx = null;
            ctx = null;
            System.gc();
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    return (sRet);
}