Example usage for android.content Context getFilesDir

List of usage examples for android.content Context getFilesDir

Introduction

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

Prototype

public abstract File getFilesDir();

Source Link

Document

Returns the absolute path to the directory on the filesystem where files created with #openFileOutput are stored.

Usage

From source file:com.psiphon3.psiphonlibrary.TunnelManager.java

/**
 * Create a tunnel-core config suitable for different tunnel types (i.e., the main Psiphon app
 * tunnel and the UpgradeChecker temp tunnel).
 *
 * @param context// ww w .  ja va  2 s  .  c  o  m
 * @param tempTunnelName       null if not a temporary tunnel. If set, must be a valid to use in file path.
 * @param clientPlatformPrefix null if not applicable (i.e., for main Psiphon app); should be provided
 *                             for temp tunnels. Will be prepended to standard client platform value.
 * @return JSON string of config. null on error.
 */
public static String buildTunnelCoreConfig(Context context, Config tunnelConfig, String tempTunnelName,
        String clientPlatformPrefix) {
    boolean temporaryTunnel = tempTunnelName != null && !tempTunnelName.isEmpty();

    JSONObject json = new JSONObject();

    try {
        String clientPlatform = PsiphonConstants.PLATFORM;

        if (clientPlatformPrefix != null && !clientPlatformPrefix.isEmpty()) {
            clientPlatform = clientPlatformPrefix + clientPlatform;
        }

        // Detect if device is rooted and append to the client_platform string
        if (Utils.isRooted()) {
            clientPlatform += PsiphonConstants.ROOTED;
        }

        // Detect if this is a Play Store build
        if (EmbeddedValues.IS_PLAY_STORE_BUILD) {
            clientPlatform += PsiphonConstants.PLAY_STORE_BUILD;
        }

        json.put("ClientPlatform", clientPlatform);

        json.put("ClientVersion", EmbeddedValues.CLIENT_VERSION);

        if (UpgradeChecker.upgradeCheckNeeded(context)) {

            json.put("UpgradeDownloadURLs", new JSONArray(EmbeddedValues.UPGRADE_URLS_JSON));

            json.put("UpgradeDownloadClientVersionHeader", "x-amz-meta-psiphon-client-version");

            json.put("UpgradeDownloadFilename",
                    new UpgradeManager.DownloadedUpgradeFile(context).getFullPath());
        }

        json.put("PropagationChannelId", EmbeddedValues.PROPAGATION_CHANNEL_ID);

        json.put("SponsorId", EmbeddedValues.SPONSOR_ID);

        json.put("RemoteServerListURLs", new JSONArray(EmbeddedValues.REMOTE_SERVER_LIST_URLS_JSON));

        json.put("ObfuscatedServerListRootURLs",
                new JSONArray(EmbeddedValues.OBFUSCATED_SERVER_LIST_ROOT_URLS_JSON));

        json.put("RemoteServerListSignaturePublicKey", EmbeddedValues.REMOTE_SERVER_LIST_SIGNATURE_PUBLIC_KEY);

        json.put("UpstreamProxyUrl", UpstreamProxySettings.getUpstreamProxyUrl(context));

        json.put("EmitDiagnosticNotices", true);

        // If this is a temporary tunnel (like for UpgradeChecker) we need to override some of
        // the implicit config values.
        if (temporaryTunnel) {
            File tempTunnelDir = new File(context.getFilesDir(), tempTunnelName);
            if (!tempTunnelDir.exists() && !tempTunnelDir.mkdirs()) {
                // Failed to create DB directory
                return null;
            }

            // On Android, these directories must be set to the app private storage area.
            // The Psiphon library won't be able to use its current working directory
            // and the standard temporary directories do not exist.
            json.put("DataStoreDirectory", tempTunnelDir.getAbsolutePath());

            File remoteServerListDownload = new File(tempTunnelDir, "remote_server_list");
            json.put("RemoteServerListDownloadFilename", remoteServerListDownload.getAbsolutePath());

            File oslDownloadDir = new File(tempTunnelDir, "osl");
            if (!oslDownloadDir.exists() && !oslDownloadDir.mkdirs()) {
                // Failed to create osl directory
                // TODO: proceed anyway?
                return null;
            }
            json.put("ObfuscatedServerListDownloadDirectory", oslDownloadDir.getAbsolutePath());

            // This number is an arbitrary guess at what might be the "best" balance between
            // wake-lock-battery-burning and successful upgrade downloading.
            // Note that the fall-back untunneled upgrade download doesn't start for 30 secs,
            // so we should be waiting longer than that.
            json.put("EstablishTunnelTimeoutSeconds", 300);

            json.put("TunnelWholeDevice", 0);

            json.put("LocalHttpProxyPort", 0);
            json.put("LocalSocksProxyPort", 0);

            json.put("EgressRegion", "");
        } else {
            // TODO: configure local proxy ports
            json.put("LocalHttpProxyPort", 0);
            json.put("LocalSocksProxyPort", 0);

            String egressRegion = tunnelConfig.egressRegion;
            MyLog.g("EgressRegion", "regionCode", egressRegion);
            json.put("EgressRegion", egressRegion);
        }

        if (tunnelConfig.disableTimeouts) {
            //disable timeouts
            MyLog.g("DisableTimeouts", "disableTimeouts", true);
            json.put("TunnelConnectTimeoutSeconds", 0);
            json.put("TunnelPortForwardDialTimeoutSeconds", 0);
            json.put("TunnelSshKeepAliveProbeTimeoutSeconds", 0);
            json.put("TunnelSshKeepAlivePeriodicTimeoutSeconds", 0);
            json.put("FetchRemoteServerListTimeoutSeconds", 0);
            json.put("PsiphonApiServerTimeoutSeconds", 0);
            json.put("FetchRoutesTimeoutSeconds", 0);
            json.put("HttpProxyOriginServerTimeoutSeconds", 0);
        }

        return json.toString();
    } catch (JSONException e) {
        return null;
    }
}

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

public static void deleteAllSharedFiles(Context context, String tag) {
    String fileDir = context.getFilesDir().toString() + "/" + MMS_SHARED_FILES_FOLDER_NAME;
    File[] allFiles = new File(fileDir).listFiles();
    if (allFiles == null) {
        return;/*from  w w  w  .j av  a  2 s .com*/
    }

    for (int i = 0; i < allFiles.length; i++) {
        File file = allFiles[i];
        if (file.getName().contains(tag)) {
            MmsLog.d(TAG, "getPreviewFileUri, delete old preview file: " + file.getPath());
            file.delete();
        }
    }
}

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

public static File createTempFileExposed(Context context, Uri fromUri, String fileName) {
    MmsLog.i(TAG, "createTempFileExposed, file name: " + fileName + " Uri: " + fromUri);
    File file = null;/*  w w  w  .  j  a v  a  2s  .co  m*/
    try {
        File baseDir = context.getFilesDir();
        File folder = new File(baseDir.toString() + "/" + MMS_SHARED_FILES_FOLDER_NAME);
        if (!folder.exists()) {
            folder.mkdirs();
            folder.setExecutable(true, false);
        }
        file = new File(folder.toString() + "/" + TEMP_FILE_TAG + fileName);
        InputStream in = null;
        FileOutputStream out = null;
        try {
            in = context.getContentResolver().openInputStream(fromUri);
            out = new FileOutputStream(file);
            byte[] buf = new byte[8096];
            int seg = 0;
            while ((seg = in.read(buf)) != -1) {
                out.write(buf, 0, seg);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    } catch (FileNotFoundException e) {
        MmsLog.e(TAG, "createTempFileExposed, file not found " + fromUri + ", exception ", e);
    } catch (IOException e) {
        MmsLog.e(TAG, "createTempFileExposed, ioexception " + fromUri + ", exception ", e);
    }
    return file;
}

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

/**
 * Load installed (user or system) packages.
 *
 * TODO - include/*from ww  w  .j a  va2  s. c o  m*/
 *    /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.mozilla.SUTAgentAndroid.service.DoCommand.java

public String GetTmpDir() {
    String sRet = "";
    Context ctx = contextWrapper.getApplicationContext();
    File dir = ctx.getFilesDir();
    ctx = null;// w ww. ja v a 2 s.c om
    try {
        sRet = dir.getCanonicalPath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return (sRet);
}

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

public String StrtUpdtOMatic(String sPkgName, String sPkgFileName, String sCallBackIP, String sCallBackPort) {
    String sRet = "";

    Context ctx = contextWrapper.getApplicationContext();
    PackageManager pm = ctx.getPackageManager();

    Intent prgIntent = new Intent();
    prgIntent.setPackage("com.mozilla.watcher");

    try {/*from   w  ww  .  ja va  2s .  com*/
        PackageInfo pi = pm.getPackageInfo("com.mozilla.watcher",
                PackageManager.GET_SERVICES | PackageManager.GET_INTENT_FILTERS);
        ServiceInfo[] si = pi.services;
        for (int i = 0; i < si.length; i++) {
            ServiceInfo s = si[i];
            if (s.name.length() > 0) {
                prgIntent.setClassName(s.packageName, s.name);
                break;
            }
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        sRet = sErrorPrefix + "watcher is not properly installed";
        return (sRet);
    }

    prgIntent.putExtra("command", "updt");
    prgIntent.putExtra("pkgName", sPkgName);
    prgIntent.putExtra("pkgFile", sPkgFileName);
    prgIntent.putExtra("reboot", true);

    try {
        if ((sCallBackIP != null) && (sCallBackPort != null) && (sCallBackIP.length() > 0)
                && (sCallBackPort.length() > 0)) {
            FileOutputStream fos = ctx.openFileOutput("update.info",
                    Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
            String sBuffer = sCallBackIP + "," + sCallBackPort + "\rupdate started " + sPkgName + " "
                    + sPkgFileName + "\r";
            fos.write(sBuffer.getBytes());
            fos.flush();
            fos.close();
            fos = null;
            prgIntent.putExtra("outFile", ctx.getFilesDir() + "/update.info");
        } else {
            if (prgIntent.hasExtra("outFile")) {
                System.out.println("outFile extra unset from intent");
                prgIntent.removeExtra("outFile");
            }
        }

        ComponentName cn = contextWrapper.startService(prgIntent);
        if (cn != null)
            sRet = "exit";
        else
            sRet = sErrorPrefix + "Unable to use watcher service";
    } catch (ActivityNotFoundException anf) {
        sRet = sErrorPrefix + "Activity Not Found Exception [updt] call failed";
        anf.printStackTrace();
    } catch (FileNotFoundException e) {
        sRet = sErrorPrefix + "File creation error [updt] call failed";
        e.printStackTrace();
    } catch (IOException e) {
        sRet = sErrorPrefix + "File error [updt] call failed";
        e.printStackTrace();
    }

    ctx = null;

    return (sRet);
}

From source file:com.farmerbb.taskbar.receiver.ReceiveSettingsReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    // Ignore this broadcast if this is the free version
    if (BuildConfig.APPLICATION_ID.equals(BuildConfig.PAID_APPLICATION_ID)) {
        // Get pinned and blocked apps
        PinnedBlockedApps pba = PinnedBlockedApps.getInstance(context);
        pba.clear(context);/*from ww w .jav a 2  s  . c  o m*/

        String[] pinnedAppsPackageNames = intent.getStringArrayExtra("pinned_apps_package_names");
        String[] pinnedAppsComponentNames = intent.getStringArrayExtra("pinned_apps_component_names");
        String[] pinnedAppsLabels = intent.getStringArrayExtra("pinned_apps_labels");
        long[] pinnedAppsUserIds = intent.getLongArrayExtra("pinned_apps_user_ids");

        UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);

        if (pinnedAppsPackageNames != null && pinnedAppsComponentNames != null && pinnedAppsLabels != null)
            for (int i = 0; i < pinnedAppsPackageNames.length; i++) {
                Intent throwaway = new Intent();
                throwaway.setComponent(ComponentName.unflattenFromString(pinnedAppsComponentNames[i]));

                long userId;
                if (pinnedAppsUserIds != null)
                    userId = pinnedAppsUserIds[i];
                else
                    userId = userManager.getSerialNumberForUser(Process.myUserHandle());

                AppEntry newEntry = new AppEntry(pinnedAppsPackageNames[i], pinnedAppsComponentNames[i],
                        pinnedAppsLabels[i],
                        IconCache.getInstance(context).getIcon(context, context.getPackageManager(),
                                launcherApps.resolveActivity(throwaway,
                                        userManager.getUserForSerialNumber(userId))),
                        true);

                newEntry.setUserId(userId);
                pba.addPinnedApp(context, newEntry);
            }

        String[] blockedAppsPackageNames = intent.getStringArrayExtra("blocked_apps_package_names");
        String[] blockedAppsComponentNames = intent.getStringArrayExtra("blocked_apps_component_names");
        String[] blockedAppsLabels = intent.getStringArrayExtra("blocked_apps_labels");

        if (blockedAppsPackageNames != null && blockedAppsComponentNames != null && blockedAppsLabels != null)
            for (int i = 0; i < blockedAppsPackageNames.length; i++) {
                pba.addBlockedApp(context, new AppEntry(blockedAppsPackageNames[i],
                        blockedAppsComponentNames[i], blockedAppsLabels[i], null, false));
            }

        // Get blacklist
        Blacklist blacklist = Blacklist.getInstance(context);
        blacklist.clear(context);

        String[] blacklistPackageNames = intent.getStringArrayExtra("blacklist_package_names");
        String[] blacklistLabels = intent.getStringArrayExtra("blacklist_labels");

        if (blacklistPackageNames != null && blacklistLabels != null)
            for (int i = 0; i < blacklistPackageNames.length; i++) {
                blacklist.addBlockedApp(context,
                        new BlacklistEntry(blacklistPackageNames[i], blacklistLabels[i]));
            }

        // Get top apps
        TopApps topApps = TopApps.getInstance(context);
        topApps.clear(context);

        String[] topAppsPackageNames = intent.getStringArrayExtra("top_apps_package_names");
        String[] topAppsLabels = intent.getStringArrayExtra("top_apps_labels");

        if (topAppsPackageNames != null && topAppsLabels != null)
            for (int i = 0; i < topAppsPackageNames.length; i++) {
                topApps.addTopApp(context, new BlacklistEntry(topAppsPackageNames[i], topAppsLabels[i]));
            }

        // Get saved window sizes
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            SavedWindowSizes savedWindowSizes = SavedWindowSizes.getInstance(context);
            savedWindowSizes.clear(context);

            String[] savedWindowSizesComponentNames = intent
                    .getStringArrayExtra("saved_window_sizes_component_names");
            String[] savedWindowSizesWindowSizes = intent
                    .getStringArrayExtra("saved_window_sizes_window_sizes");

            if (savedWindowSizesComponentNames != null && savedWindowSizesWindowSizes != null)
                for (int i = 0; i < savedWindowSizesComponentNames.length; i++) {
                    savedWindowSizes.setWindowSize(context, savedWindowSizesComponentNames[i],
                            savedWindowSizesWindowSizes[i]);
                }
        }

        // Get shared preferences
        String contents = intent.getStringExtra("preferences");
        if (contents.length() > 0)
            try {
                File file = new File(context.getFilesDir().getParent() + "/shared_prefs/"
                        + BuildConfig.APPLICATION_ID + "_preferences.xml");
                FileOutputStream output = new FileOutputStream(file);
                output.write(contents.getBytes());
                output.close();
            } catch (IOException e) {
                /* Gracefully fail */ }

        try {
            File file = new File(context.getFilesDir() + File.separator + "imported_successfully");
            if (file.createNewFile())
                LocalBroadcastManager.getInstance(context)
                        .sendBroadcast(new Intent("com.farmerbb.taskbar.IMPORT_FINISHED"));
        } catch (IOException e) {
            /* Gracefully fail */ }
    }
}

From source file:processing.core.PApplet.java

/** Called with the activity is first created. */
@Override/*from w  w  w  .j av a  2s . co m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    // println("PApplet.onCreate()");

    if (DEBUG)
        println("onCreate() happening here: " + Thread.currentThread().getName());

    // commented to use fragments
    /*
     * Window window = getWindow();
     * 
     * // Take up as much area as possible
     * requestWindowFeature(Window.FEATURE_NO_TITLE);
     * window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
     * WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
     * 
     * // This does the actual full screen work
     * window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     * WindowManager.LayoutParams.FLAG_FULLSCREEN);
     */

    DisplayMetrics dm = new DisplayMetrics();
    this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
    displayWidth = dm.widthPixels;
    displayHeight = dm.heightPixels;
    // println("density is " + dm.density);
    // println("densityDpi is " + dm.densityDpi);
    if (DEBUG)
        println("display metrics: " + dm);

    // println("screen size is " + screenWidth + "x" + screenHeight);

    // LinearLayout layout = new LinearLayout(this);
    // layout.setOrientation(LinearLayout.VERTICAL |
    // LinearLayout.HORIZONTAL);
    // viewGroup = new ViewGroup();
    // surfaceView.setLayoutParams();
    // viewGroup.setLayoutParams(LayoutParams.)
    // RelativeLayout layout = new RelativeLayout(this);
    // RelativeLayout overallLayout = new RelativeLayout(this);
    // RelativeLayout.LayoutParams lp = new
    // RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
    // RelativeLayout.LayoutParams.FILL_PARENT);
    // lp.addRule(RelativeLayout.RIGHT_OF, tv1.getId());
    // layout.setGravity(RelativeLayout.CENTER_IN_PARENT);

    int sw = sketchWidth();
    int sh = sketchHeight();

    if (sketchRenderer().equals(JAVA2D)) {
        surfaceView = new SketchSurfaceView(this.getActivity(), sw, sh);
    } else if (sketchRenderer().equals(P2D) || sketchRenderer().equals(P3D)) {
        surfaceView = new SketchSurfaceViewGL(this.getActivity(), sw, sh, sketchRenderer().equals(P3D));
    }
    // g = ((SketchSurfaceView) surfaceView).getGraphics();

    // surfaceView.setLayoutParams(new LayoutParams(sketchWidth(),
    // sketchHeight()));

    // layout.addView(surfaceView);
    // surfaceView.setVisibility(1);
    // println("visibility " + surfaceView.getVisibility() + " " +
    // SurfaceView.VISIBLE);
    // layout.addView(surfaceView);
    // AttributeSet as = new AttributeSet();
    // RelativeLayout.LayoutParams lp = new
    // RelativeLayout.LayoutParams(layout, as);

    // lp.addRule(android.R.styleable.ViewGroup_Layout_layout_height,
    // layout.add
    // lp.addRule(, arg1)
    // layout.addView(surfaceView, sketchWidth(), sketchHeight());

    // new
    // RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
    // RelativeLayout.LayoutParams.FILL_PARENT);

    if (sw == displayWidth && sh == displayHeight) {
        // If using the full screen, don't embed inside other layouts
        // window.setContentView(surfaceView); no para fragments
    } else {
        // If not using full screen, setup awkward view-inside-a-view so
        // that
        // the sketch can be centered on screen. (If anyone has a more
        // efficient
        // way to do this, please file an issue on Google Code, otherwise
        // you
        // can keep your "talentless hack" comments to yourself. Ahem.)
        RelativeLayout overallLayout = new RelativeLayout(this.getActivity());
        overallLayout.setBackgroundColor(0x00000000);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        LinearLayout layout = new LinearLayout(this.getActivity());
        layout.setBackgroundColor(0x00000000);
        layout.addView(surfaceView, sketchWidth(), sketchHeight());
        overallLayout.addView(layout, lp);
        // window.setContentView(overallLayout); no para fragments
    }

    /*
     * // Here we use Honeycomb API (11+) to hide (in reality, just make the
     * status icons into small dots) // the status bar. Since the core is
     * still built against API 7 (2.1), we use introspection to get // the
     * setSystemUiVisibility() method from the view class. Method
     * visibilityMethod = null; try { visibilityMethod =
     * surfaceView.getClass().getMethod("setSystemUiVisibility", new Class[]
     * { int.class}); } catch (NoSuchMethodException e) { // Nothing to do.
     * This means that we are running with a version of Android previous to
     * Honeycomb. } if (visibilityMethod != null) { try { // This is
     * equivalent to calling:
     * //surfaceView.setSystemUiVisibility(View.STATUS_BAR_HIDDEN); // The
     * value of View.STATUS_BAR_HIDDEN is 1.
     * visibilityMethod.invoke(surfaceView, new Object[] { 1 }); } catch
     * (InvocationTargetException e) { } catch (IllegalAccessException e) {
     * } } window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     * WindowManager.LayoutParams.FLAG_FULLSCREEN);
     */

    // layout.addView(surfaceView, lp);
    // surfaceView.setLayoutParams(new LayoutParams(sketchWidth(),
    // sketchHeight()));

    // RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams()
    // layout.addView(surfaceView, new LayoutParams(arg0)

    // TODO probably don't want to set these here, can't we wait for
    // surfaceChanged()?
    // removing this in 0187
    // width = screenWidth;
    // height = screenHeight;

    // int left = (screenWidth - iwidth) / 2;
    // int right = screenWidth - (left + iwidth);
    // int top = (screenHeight - iheight) / 2;
    // int bottom = screenHeight - (top + iheight);
    // surfaceView.setPadding(left, top, right, bottom);
    // android:layout_width

    // window.setContentView(surfaceView); // set full screen

    // code below here formerly from init()

    // millisOffset = System.currentTimeMillis(); // moved to the variable
    // declaration

    finished = false; // just for clarity

    // this will be cleared by draw() if it is not overridden
    looping = true;
    redraw = true; // draw this guy once
    firstMotion = true;

    // these need to be inited before setup
    sizeMethods = new RegisteredMethods();
    preMethods = new RegisteredMethods();
    drawMethods = new RegisteredMethods();
    postMethods = new RegisteredMethods();
    mouseEventMethods = new RegisteredMethods();
    keyEventMethods = new RegisteredMethods();
    disposeMethods = new RegisteredMethods();

    Context context = this.getActivity().getApplicationContext();
    sketchPath = context.getFilesDir().getAbsolutePath();

    // Looper.prepare();
    handler = new Handler();
    // println("calling loop()");
    // Looper.loop();
    // println("done with loop() call, will continue...");

    start();
    return surfaceView;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * Retrieves the app's available push action categories from the XML file in which they
 * should have been installed on the first load.
 * @param context/* ww w  .  j ava 2s . c o m*/
 * @return
 * @throws IOException 
 */
private static PushActionCategory[] getInstalledPushActionCategories(Context context) throws IOException {
    // NOTE:  This method may be called from the PushReceiver when the app isn't running so we can't access
    // the main activity context, display properties, or any CN1 stuff.  Just native android

    File categoriesFile = new File(
            context.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES);
    if (!categoriesFile.exists()) {
        return new PushActionCategory[0];
    }
    javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory
            .newInstance();
    javax.xml.parsers.DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException(
                "Faield to create document builder for creating notification categories XML document", ex);
    }
    org.w3c.dom.Document doc;
    try {
        doc = docBuilder.parse(context.openFileInput(FILE_NAME_NOTIFICATION_CATEGORIES));
    } catch (SAXException ex) {
        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException("Failed to parse instaled push action categories", ex);
    }
    org.w3c.dom.Element root = doc.getDocumentElement();
    java.util.List<PushActionCategory> out = new ArrayList<PushActionCategory>();
    org.w3c.dom.NodeList l = root.getElementsByTagName("category");
    int len = l.getLength();
    for (int i = 0; i < len; i++) {
        org.w3c.dom.Element el = (org.w3c.dom.Element) l.item(i);
        java.util.List<PushAction> actions = new ArrayList<PushAction>();
        org.w3c.dom.NodeList al = el.getElementsByTagName("action");
        int alen = al.getLength();
        for (int j = 0; j < alen; j++) {
            org.w3c.dom.Element actionEl = (org.w3c.dom.Element) al.item(j);
            String textInputPlaceholder = actionEl.hasAttribute("textInputPlaceholder")
                    ? actionEl.getAttribute("textInputPlaceholder")
                    : null;
            String textInputButtonText = actionEl.hasAttribute("textInputButtonText")
                    ? actionEl.getAttribute("textInputButtonText")
                    : null;
            PushAction action = new PushAction(actionEl.getAttribute("id"), actionEl.getAttribute("title"),
                    actionEl.getAttribute("icon"), textInputPlaceholder, textInputButtonText);
            actions.add(action);
        }

        PushActionCategory cat = new PushActionCategory((String) el.getAttribute("id"),
                actions.toArray(new PushAction[actions.size()]));
        out.add(cat);

    }
    return out.toArray(new PushActionCategory[out.size()]);
}

From source file:com.processing.core.PApplet.java

/** Called with the activity is first created. */
@Override/*from  ww w.  j ava2  s  . c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //    println("PApplet.onCreate()");

    if (DEBUG)
        println("onCreate() happening here: " + Thread.currentThread().getName());

    Window window = getWindow();

    // Take up as much area as possible
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);

    // This does the actual full screen work
    window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    displayWidth = dm.widthPixels;
    displayHeight = dm.heightPixels;
    //    println("density is " + dm.density);
    //    println("densityDpi is " + dm.densityDpi);
    if (DEBUG)
        println("display metrics: " + dm);

    //println("screen size is " + screenWidth + "x" + screenHeight);

    //    LinearLayout layout = new LinearLayout(this);
    //    layout.setOrientation(LinearLayout.VERTICAL | LinearLayout.HORIZONTAL);
    //    viewGroup = new ViewGroup();
    //    surfaceView.setLayoutParams();
    //    viewGroup.setLayoutParams(LayoutParams.)
    //    RelativeLayout layout = new RelativeLayout(this);
    //    RelativeLayout overallLayout = new RelativeLayout(this);
    //    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
    //lp.addRule(RelativeLayout.RIGHT_OF, tv1.getId());
    //    layout.setGravity(RelativeLayout.CENTER_IN_PARENT);

    int sw = sketchWidth();
    int sh = sketchHeight();

    if (sketchRenderer().equals(JAVA2D)) {
        surfaceView = new SketchSurfaceView(this, sw, sh);
    } else if (sketchRenderer().equals(P2D) || sketchRenderer().equals(P3D)) {
        surfaceView = new SketchSurfaceViewGL(this, sw, sh, sketchRenderer().equals(P3D));
    }
    //    g = ((SketchSurfaceView) surfaceView).getGraphics();

    //    surfaceView.setLayoutParams(new LayoutParams(sketchWidth(), sketchHeight()));

    //    layout.addView(surfaceView);
    //    surfaceView.setVisibility(1);
    //    println("visibility " + surfaceView.getVisibility() + " " + SurfaceView.VISIBLE);
    //    layout.addView(surfaceView);
    //    AttributeSet as = new AttributeSet();
    //    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(layout, as);

    //    lp.addRule(android.R.styleable.ViewGroup_Layout_layout_height,
    //    layout.add
    //lp.addRule(, arg1)
    //layout.addView(surfaceView, sketchWidth(), sketchHeight());

    //      new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
    //        RelativeLayout.LayoutParams.FILL_PARENT);

    if (sw == displayWidth && sh == displayHeight) {
        // If using the full screen, don't embed inside other layouts
        window.setContentView(surfaceView);
    } else {
        // If not using full screen, setup awkward view-inside-a-view so that
        // the sketch can be centered on screen. (If anyone has a more efficient
        // way to do this, please file an issue on Google Code, otherwise you
        // can keep your "talentless hack" comments to yourself. Ahem.)
        RelativeLayout overallLayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        LinearLayout layout = new LinearLayout(this);
        layout.addView(surfaceView, sketchWidth(), sketchHeight());
        overallLayout.addView(layout, lp);
        window.setContentView(overallLayout);
    }

    /*
    // Here we use Honeycomb API (11+) to hide (in reality, just make the status icons into small dots)
    // the status bar. Since the core is still built against API 7 (2.1), we use introspection to get
    // the setSystemUiVisibility() method from the view class.
    Method visibilityMethod = null;
    try {
      visibilityMethod = surfaceView.getClass().getMethod("setSystemUiVisibility", new Class[] { int.class});
    } catch (NoSuchMethodException e) {
      // Nothing to do. This means that we are running with a version of Android previous to Honeycomb.
    }
    if (visibilityMethod != null) {
      try {
        // This is equivalent to calling:
        //surfaceView.setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
        // The value of View.STATUS_BAR_HIDDEN is 1.
        visibilityMethod.invoke(surfaceView, new Object[] { 1 });
      } catch (InvocationTargetException e) {
      } catch (IllegalAccessException e) {
      }
    }
    window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    */

    //    layout.addView(surfaceView, lp);
    //    surfaceView.setLayoutParams(new LayoutParams(sketchWidth(), sketchHeight()));

    //    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams()
    //    layout.addView(surfaceView, new LayoutParams(arg0)

    // TODO probably don't want to set these here, can't we wait for surfaceChanged()?
    // removing this in 0187
    //    width = screenWidth;
    //    height = screenHeight;

    //    int left = (screenWidth - iwidth) / 2;
    //    int right = screenWidth - (left + iwidth);
    //    int top = (screenHeight - iheight) / 2;
    //    int bottom = screenHeight - (top + iheight);
    //    surfaceView.setPadding(left, top, right, bottom);
    // android:layout_width

    //    window.setContentView(surfaceView);  // set full screen

    // code below here formerly from init()

    //millisOffset = System.currentTimeMillis(); // moved to the variable declaration

    finished = false; // just for clarity

    // this will be cleared by draw() if it is not overridden
    looping = true;
    redraw = true; // draw this guy once
    //    firstMotion = true;

    Context context = getApplicationContext();
    sketchPath = context.getFilesDir().getAbsolutePath();

    //    Looper.prepare();
    handler = new Handler();
    //    println("calling loop()");
    //    Looper.loop();
    //    println("done with loop() call, will continue...");

    start();
}