Example usage for android.os StatFs StatFs

List of usage examples for android.os StatFs StatFs

Introduction

In this page you can find the example usage for android.os StatFs StatFs.

Prototype

public StatFs(String path) 

Source Link

Document

Construct a new StatFs for looking at the stats of the filesystem at path .

Usage

From source file:org.uguess.android.sysinfo.SiragonManager.java

/**
 * This checks the built-in app2sd storage info supported since Froyo
 *///w w w .jav  a2  s  .c om
private String[] getSystemA2SDStorageInfo() {
    Activity ctx = getActivity();
    final PackageManager pm = ctx.getPackageManager();
    List<ApplicationInfo> allApps = pm.getInstalledApplications(0);

    long total = 0;
    long free = 0;

    for (int i = 0, size = allApps.size(); i < size; i++) {
        ApplicationInfo info = allApps.get(i);

        if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
            String src = info.sourceDir;

            if (src != null) {
                File srcFile = new File(src);

                if (srcFile.canRead()) {
                    try {
                        StatFs stat = new StatFs(srcFile.getAbsolutePath());
                        long blockSize = stat.getBlockSize();

                        total += stat.getBlockCount() * blockSize;
                        free += stat.getAvailableBlocks() * blockSize;
                    } catch (Exception e) {
                        Log.e(SiragonManager.class.getName(), "Cannot access path: " //$NON-NLS-1$
                                + srcFile.getAbsolutePath(), e);
                    }
                }
            }
        }
    }

    if (total > 0) {
        String[] info = new String[2];
        info[0] = Formatter.formatFileSize(ctx, total);
        info[1] = Formatter.formatFileSize(ctx, free);

        return info;
    }

    return null;
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

public static long getAvailableExternalMemorySize() {
    if (externalMemoryAvailable()) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    } else {//from w  w w  .  j a va 2  s .com
        return 0;
    }
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

public static long getTotalExternalMemorySize() {
    if (externalMemoryAvailable()) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    } else {//from   w w  w.  j  a v a2  s.c  om
        return 0;
    }
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

private String[] getStorageInfo(File path) {
    if (path != null) {
        try {/*from w  ww.j  a  va  2  s  .co  m*/
            Activity ctx = getActivity();

            StatFs stat = new StatFs(path.getAbsolutePath());
            long blockSize = stat.getBlockSize();

            String[] info = new String[2];
            info[0] = Formatter.formatFileSize(ctx, stat.getBlockCount() * blockSize);
            info[1] = Formatter.formatFileSize(ctx, stat.getAvailableBlocks() * blockSize);

            return info;
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), "Cannot access path: " //$NON-NLS-1$
                    + path.getAbsolutePath(), e);
        }
    }

    return null;
}

From source file:com.rareventure.gps2.GTG.java

/**
 * If there is a serious problem that would prevent the application from running
 * successfully, this will create an alert and return true.
 * Otherwise if things are good to go, it returns false
 *//*from ww w.jav  a2 s .c  om*/
public static boolean checkSdCard(Context context) {
    if (!sdCardMounted(context)) {
        GTG.alert(GTGEvent.ERROR_SDCARD_NOT_MOUNTED);
        return false;
    }

    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    long sdAvailSize = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();

    if (sdAvailSize < MIN_FREE_SPACE_ON_SDCARD) {
        GTG.alert(GTGEvent.ERROR_LOW_FREE_SPACE);
        return false;
    }

    return true;

}

From source file:com.almalence.opencam.ApplicationScreen.java

protected long getAvailableInternalMemory() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long availableBlocks = stat.getAvailableBlocks();
    return availableBlocks * blockSize / 1048576;
}

From source file:com.horizondigital.delta.UpdateService.java

private void checkForUpdatesAsync(boolean userInitiated) {
    updateState(STATE_ACTION_CHECKING, null, null, null, null, null);
    wakeLock.acquire();/*  ww w. j a  v  a  2  s . co  m*/
    wifiLock.acquire();

    stopNotification();

    Notification notification = (new Notification.Builder(this)).setSmallIcon(R.drawable.stat_notify_update)
            .setContentTitle(getString(R.string.title)).setContentText(getString(R.string.notify_checking))
            .setTicker(getString(R.string.notify_checking)).setShowWhen(false)
            .setContentIntent(getNotificationIntent(false)).build();
    startForeground(NOTIFICATION_BUSY, notification);

    final boolean force = userInitiated;

    handler.post(new Runnable() {
        @Override
        public void run() {
            try {
                List<DeltaInfo> deltas = new ArrayList<DeltaInfo>();

                String flashFilename = null;
                (new File(path_base)).mkdir();
                (new File(path_flash_after_update)).mkdir();

                // Create a list of deltas to apply to get from our current
                // version to the latest
                String fetch = String.format(Locale.ENGLISH, "%s%s-%s.delta", url_base_delta, filename_base,
                        property_device);
                while (true) {
                    DeltaInfo delta = null;

                    try {
                        delta = new DeltaInfo(downloadUrlMemory(fetch), false);
                    } catch (JSONException e) {
                        // There's an error in the JSON. Could be bad JSON, could be a 404 text, etc
                        Logger.ex(e);
                    } catch (NullPointerException e) {
                        // Download failed
                        Logger.ex(e);
                    }

                    if (delta == null) {
                        // See if we have a revoked version instead, we
                        // still need it for chaining future deltas, but
                        // will not allow flashing this one
                        try {
                            delta = new DeltaInfo(downloadUrlMemory(fetch.replace(".delta", ".delta_revoked")),
                                    true);
                        } catch (JSONException e) {
                            // There's an error in the JSON. Could be bad JSON, could be a 404 text, etc
                            Logger.ex(e);
                        } catch (NullPointerException e) {
                            // Download failed
                            Logger.ex(e);
                        }

                        // We didn't get a delta or a delta_revoked - end of the delta availability chain
                        if (delta == null)
                            break;
                    }

                    Logger.d("delta --> [%s]", delta.getOut().getName());
                    fetch = String.format(Locale.ENGLISH, "%s%s.delta", url_base_delta,
                            delta.getOut().getName().replace(".zip", ""));
                    deltas.add(delta);
                }

                if (deltas.size() > 0) {
                    // See if we have done past work and have newer ZIPs
                    // than the original of what's currently flashed

                    int last = -1;
                    for (int i = deltas.size() - 1; i >= 0; i--) {
                        DeltaInfo di = deltas.get(i);
                        String fn = path_base + di.getOut().getName();
                        if (di.getOut().match(new File(fn), true,
                                getMD5Progress(STATE_ACTION_CHECKING_MD5, di.getOut().getName())) != null) {
                            Logger.d("match found: %s", di.getOut().getName());
                            flashFilename = fn;
                            last = i;
                            break;
                        }
                    }

                    if (last > -1) {
                        for (int i = 0; i <= last; i++) {
                            deltas.remove(0);
                        }
                    }
                }

                while ((deltas.size() > 0) && (deltas.get(deltas.size() - 1).isRevoked())) {
                    // Make sure the last delta is not revoked
                    deltas.remove(deltas.size() - 1);
                }

                if (deltas.size() > 0) {
                    DeltaInfo lastDelta = deltas.get(deltas.size() - 1);

                    long deltaDownloadSize = getDeltaDownloadSize(deltas);
                    long fullDownloadSize = getFullDownloadSize(deltas);

                    Logger.d("download size --> deltas[%d] vs full[%d]", deltaDownloadSize, fullDownloadSize);

                    // Find the currently flashed ZIP, or a newer one
                    String initialFile = null;
                    boolean initialFileNeedsProcessing = false;
                    {
                        boolean[] needsProcessing = new boolean[] { false };
                        initialFile = findInitialFile(deltas, flashFilename, needsProcessing);
                        initialFileNeedsProcessing = needsProcessing[0];
                    }
                    flashFilename = null;

                    Logger.d("initial: %s", initialFile != null ? initialFile : "not found");

                    // If we don't have a file to start out with, or the
                    // combined deltas get big, just get the latest full ZIP
                    boolean getFull = ((initialFile == null) || (deltaDownloadSize > fullDownloadSize));

                    long requiredSpace = getRequiredSpace(deltas, getFull);
                    long freeSpace = (new StatFs(path_base)).getAvailableBytes();
                    if (freeSpace < requiredSpace) {
                        updateState(STATE_ERROR_DISK_SPACE, null, freeSpace, requiredSpace, null, null);
                        Logger.d("not enough space!");
                        return;
                    }

                    long downloadSize = getFull ? fullDownloadSize : deltaDownloadSize;

                    // Download all the files we do not have yet
                    if (!downloadFiles(deltas, getFull, downloadSize, force))
                        return;

                    // Reconstruct flashable ZIP
                    if (!getFull && !applyPatches(deltas, initialFile, initialFileNeedsProcessing))
                        return;

                    // Verify using MD5
                    if (lastDelta.getOut().match(new File(path_base + lastDelta.getOut().getName()), true,
                            getMD5Progress(STATE_ACTION_APPLYING_MD5, lastDelta.getOut().getName())) == null) {
                        updateState(STATE_ERROR_UNKNOWN, null, null, null, null, null);
                        Logger.d("final verification error");
                        return;
                    }
                    Logger.d("final verification complete");

                    // Cleanup
                    for (DeltaInfo di : deltas) {
                        (new File(path_base + di.getUpdate().getName())).delete();
                        (new File(path_base + di.getSignature().getName())).delete();
                        if (di != lastDelta)
                            (new File(path_base + di.getOut().getName())).delete();
                    }
                    if (initialFile != null) {
                        if (initialFile.startsWith(path_base))
                            (new File(initialFile)).delete();
                    }

                    flashFilename = path_base + lastDelta.getOut().getName();
                }

                if (flashFilename != null) {
                    prefs.edit().putString(PREF_READY_FILENAME_NAME, flashFilename).commit();
                }

                prefs.edit().putLong(PREF_LAST_CHECK_TIME_NAME, System.currentTimeMillis()).commit();
            } finally {
                stopForeground(true);
                if (wifiLock.isHeld())
                    wifiLock.release();
                if (wakeLock.isHeld())
                    wakeLock.release();
                autoState();
            }
        }
    });
}

From source file:eu.chainfire.opendelta.UpdateService.java

private void checkForUpdatesAsync(boolean userInitiated) {
    updateState(STATE_ACTION_CHECKING, null, null, null, null, null);
    wakeLock.acquire();/*w  ww .  j a v  a2 s  .  c  om*/
    wifiLock.acquire();

    stopNotification();

    Notification notification = (new Notification.Builder(this)).setSmallIcon(R.drawable.stat_notify_update)
            .setContentTitle(getString(R.string.title)).setContentText(getString(R.string.notify_checking))
            .setTicker(getString(R.string.notify_checking)).setShowWhen(false)
            .setContentIntent(getNotificationIntent(false)).build();
    startForeground(NOTIFICATION_BUSY, notification);

    final boolean force = userInitiated;

    handler.post(new Runnable() {
        @Override
        public void run() {
            try {
                List<DeltaInfo> deltas = new ArrayList<DeltaInfo>();

                String flashFilename = null;
                (new File(config.getPathBase())).mkdir();
                (new File(config.getPathFlashAfterUpdate())).mkdir();

                // Create a list of deltas to apply to get from our current
                // version to the latest
                String fetch = String.format(Locale.ENGLISH, "%s%s.delta", config.getUrlBaseDelta(),
                        config.getFilenameBase());
                while (true) {
                    DeltaInfo delta = null;

                    try {
                        delta = new DeltaInfo(downloadUrlMemory(fetch), false);
                    } catch (JSONException e) {
                        // There's an error in the JSON. Could be bad JSON,
                        // could be a 404 text, etc
                        Logger.ex(e);
                    } catch (NullPointerException e) {
                        // Download failed
                        Logger.ex(e);
                    }

                    if (delta == null) {
                        // See if we have a revoked version instead, we
                        // still need it for chaining future deltas, but
                        // will not allow flashing this one
                        try {
                            delta = new DeltaInfo(downloadUrlMemory(fetch.replace(".delta", ".delta_revoked")),
                                    true);
                        } catch (JSONException e) {
                            // There's an error in the JSON. Could be bad
                            // JSON, could be a 404 text, etc
                            Logger.ex(e);
                        } catch (NullPointerException e) {
                            // Download failed
                            Logger.ex(e);
                        }

                        // We didn't get a delta or a delta_revoked - end of
                        // the delta availability chain
                        if (delta == null)
                            break;
                    }

                    Logger.d("delta --> [%s]", delta.getOut().getName());
                    fetch = String.format(Locale.ENGLISH, "%s%s.delta", config.getUrlBaseDelta(),
                            delta.getOut().getName().replace(".zip", ""));
                    deltas.add(delta);
                }

                if (deltas.size() > 0) {
                    // See if we have done past work and have newer ZIPs
                    // than the original of what's currently flashed

                    int last = -1;
                    for (int i = deltas.size() - 1; i >= 0; i--) {
                        DeltaInfo di = deltas.get(i);
                        String fn = config.getPathBase() + di.getOut().getName();
                        if (di.getOut().match(new File(fn), true,
                                getMD5Progress(STATE_ACTION_CHECKING_MD5, di.getOut().getName())) != null) {
                            Logger.d("match found: %s", di.getOut().getName());
                            flashFilename = fn;
                            last = i;
                            break;
                        }
                    }

                    if (last > -1) {
                        for (int i = 0; i <= last; i++) {
                            deltas.remove(0);
                        }
                    }
                }

                while ((deltas.size() > 0) && (deltas.get(deltas.size() - 1).isRevoked())) {
                    // Make sure the last delta is not revoked
                    deltas.remove(deltas.size() - 1);
                }

                if (deltas.size() > 0) {
                    DeltaInfo lastDelta = deltas.get(deltas.size() - 1);

                    long deltaDownloadSize = getDeltaDownloadSize(deltas);
                    long fullDownloadSize = getFullDownloadSize(deltas);

                    Logger.d("download size --> deltas[%d] vs full[%d]", deltaDownloadSize, fullDownloadSize);

                    // Find the currently flashed ZIP, or a newer one
                    String initialFile = null;
                    boolean initialFileNeedsProcessing = false;
                    {
                        boolean[] needsProcessing = new boolean[] { false };
                        initialFile = findInitialFile(deltas, flashFilename, needsProcessing);
                        initialFileNeedsProcessing = needsProcessing[0];
                    }
                    flashFilename = null;

                    Logger.d("initial: %s", initialFile != null ? initialFile : "not found");

                    // If we don't have a file to start out with, or the
                    // combined deltas get big, just get the latest full ZIP
                    boolean getFull = ((initialFile == null) || (deltaDownloadSize > fullDownloadSize));

                    long requiredSpace = getRequiredSpace(deltas, getFull);
                    long freeSpace = (new StatFs(config.getPathBase())).getAvailableBytes();
                    if (freeSpace < requiredSpace) {
                        updateState(STATE_ERROR_DISK_SPACE, null, freeSpace, requiredSpace, null, null);
                        Logger.d("not enough space!");
                        return;
                    }

                    long downloadSize = getFull ? fullDownloadSize : deltaDownloadSize;

                    // Download all the files we do not have yet
                    if (!downloadFiles(deltas, getFull, downloadSize, force))
                        return;

                    // Reconstruct flashable ZIP
                    if (!getFull && !applyPatches(deltas, initialFile, initialFileNeedsProcessing))
                        return;

                    // Verify using MD5
                    if (lastDelta.getOut().match(new File(config.getPathBase() + lastDelta.getOut().getName()),
                            true,
                            getMD5Progress(STATE_ACTION_APPLYING_MD5, lastDelta.getOut().getName())) == null) {
                        updateState(STATE_ERROR_UNKNOWN, null, null, null, null, null);
                        Logger.d("final verification error");
                        return;
                    }
                    Logger.d("final verification complete");

                    // Cleanup
                    for (DeltaInfo di : deltas) {
                        (new File(config.getPathBase() + di.getUpdate().getName())).delete();
                        (new File(config.getPathBase() + di.getSignature().getName())).delete();
                        if (di != lastDelta)
                            (new File(config.getPathBase() + di.getOut().getName())).delete();
                    }
                    if (initialFile != null) {
                        if (initialFile.startsWith(config.getPathBase()))
                            (new File(initialFile)).delete();
                    }

                    flashFilename = config.getPathBase() + lastDelta.getOut().getName();
                }

                if (flashFilename != null) {
                    prefs.edit().putString(PREF_READY_FILENAME_NAME, flashFilename).commit();
                }

                prefs.edit().putLong(PREF_LAST_CHECK_TIME_NAME, System.currentTimeMillis()).commit();
            } finally {
                stopForeground(true);
                if (wifiLock.isHeld())
                    wifiLock.release();
                if (wakeLock.isHeld())
                    wakeLock.release();
                autoState();
            }
        }
    });
}

From source file:cm.aptoide.pt.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    AptoideThemePicker.setAptoideTheme(this);
    super.onCreate(savedInstanceState);

    serviceDownloadManagerIntent = new Intent(this, ServiceDownloadManager.class);
    startService(serviceDownloadManagerIntent);
    mContext = this;

    File sdcard_file = new File(SDCARD);
    if (!sdcard_file.exists() || !sdcard_file.canWrite()) {
        View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null);
        Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
        final AlertDialog noSDDialog = dialogBuilder.create();
        noSDDialog.setTitle(getText(R.string.remote_in_noSD_title));
        noSDDialog.setIcon(android.R.drawable.ic_dialog_alert);
        TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
        message.setText(getText(R.string.remote_in_noSD));
        noSDDialog.setCancelable(false);
        noSDDialog.setButton(Dialog.BUTTON_NEUTRAL, getString(android.R.string.ok),
                new Dialog.OnClickListener() {
                    @Override//from  w  w w  .  j  a v a  2 s .c  om
                    public void onClick(DialogInterface arg0, int arg1) {
                        finish();
                    }
                });
        noSDDialog.show();
    } else {
        StatFs stat = new StatFs(sdcard_file.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        long availableBlocks = stat.getAvailableBlocks();

        long total = (blockSize * totalBlocks) / 1024 / 1024;
        long avail = (blockSize * availableBlocks) / 1024 / 1024;
        Log.d("Aptoide", "* * * * * * * * * *");
        Log.d("Aptoide", "Total: " + total + " Mb");
        Log.d("Aptoide", "Available: " + avail + " Mb");

        if (avail < 10) {
            Log.d("Aptoide", "No space left on SDCARD...");
            Log.d("Aptoide", "* * * * * * * * * *");
            View simpleView = LayoutInflater.from(this).inflate(R.layout.dialog_simple_layout, null);
            Builder dialogBuilder = new AlertDialog.Builder(this).setView(simpleView);
            final AlertDialog noSpaceDialog = dialogBuilder.create();
            noSpaceDialog.setIcon(android.R.drawable.ic_dialog_alert);
            TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
            message.setText(getText(R.string.remote_in_noSDspace));
            noSpaceDialog.setButton(Dialog.BUTTON_NEUTRAL, getText(android.R.string.ok),
                    new Dialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            finish();
                        }
                    });
            noSpaceDialog.show();
        } else {

            SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(mContext);
            editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();

            if (!sPref.contains("matureChkBox")) {

                editor.putBoolean("matureChkBox", ApplicationAptoide.MATURECONTENTSWITCHVALUE);
                SharedPreferences sPrefOld = getSharedPreferences("aptoide_prefs", MODE_PRIVATE);
                if (sPrefOld.getString("app_rating", "none").equals("Mature")) {
                    editor.putBoolean("matureChkBox", false);
                }

            }

            if (!sPref.contains("version")) {

                ApplicationAptoide.setRestartLauncher(true);
                try {
                    editor.putInt("version",
                            getPackageManager().getPackageInfo(getPackageName(), 0).versionCode);
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }

            }

            if (sPref.getString("myId", null) == null) {
                String rand_id = UUID.randomUUID().toString();
                editor.putString("myId", rand_id);
            }

            if (sPref.getInt("scW", 0) == 0 || sPref.getInt("scH", 0) == 0) {
                DisplayMetrics dm = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dm);
                editor.putInt("scW", dm.widthPixels);
                editor.putInt("scH", dm.heightPixels);
            }
            editor.commit();
            File file = new File(LOCAL_PATH + "/apks");
            if (!file.exists()) {
                file.mkdirs();
            }

            new Thread(new Runnable() {

                @Override
                public void run() {

                    // Note the L that tells the compiler to interpret the
                    // number as a Long
                    final long MAXFILEAGE = 2678400000L; // 1 month in
                    // milliseconds

                    // Get file handle to the directory. In this case the
                    // application files dir
                    File dir = new File(LOCAL_PATH + "/apks");

                    // Optain list of files in the directory.
                    // listFiles() returns a list of File objects to each
                    // file found.
                    File[] files = dir.listFiles();

                    // Loop through all files
                    for (File f : files) {

                        // Get the last modified date. Miliseconds since
                        // 1970
                        long lastmodified = f.lastModified();

                        // Do stuff here to deal with the file..
                        // For instance delete files older than 1 month
                        if (lastmodified + MAXFILEAGE < System.currentTimeMillis()) {
                            f.delete();
                        }
                    }
                }
            }).start();
            db = Database.getInstance();

            Intent i = new Intent(mContext, MainService.class);
            startService(i);
            bindService(i, conn, Context.BIND_AUTO_CREATE);
            order = Order.values()[PreferenceManager.getDefaultSharedPreferences(mContext).getInt("order_list",
                    0)];

            registerReceiver(updatesReceiver, new IntentFilter("update"));
            registerReceiver(statusReceiver, new IntentFilter("status"));
            registerReceiver(loginReceiver, new IntentFilter("login"));
            registerReceiver(storePasswordReceiver, new IntentFilter("401"));
            registerReceiver(redrawInstalledReceiver, new IntentFilter("pt.caixamagica.aptoide.REDRAW"));
            if (!ApplicationAptoide.MULTIPLESTORES) {
                registerReceiver(parseFailedReceiver, new IntentFilter("PARSE_FAILED"));
            }

            registerReceiver(newRepoReceiver, new IntentFilter("pt.caixamagica.aptoide.NEWREPO"));
            registered = true;

            categoriesStrings = new HashMap<String, Integer>();

            //            categoriesStrings.put("Applications", R.string.applications);

            boolean serversFileIsEmpty = true;

            if (sPref.getBoolean("firstrun", true)) {
                // Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
                // shortcutIntent.setClassName("cm.aptoide.pt",
                // "cm.aptoide.pt.Start");
                // final Intent intent = new Intent();
                // intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
                // shortcutIntent);
                //
                // intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                // getString(R.string.app_name));
                // Parcelable iconResource =
                // Intent.ShortcutIconResource.fromContext(this,
                // R.drawable.ic_launcher);
                //
                // intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                // iconResource);
                // intent.putExtra("duplicate", false);
                // intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
                // sendBroadcast(intent);

                if (new File(LOCAL_PATH + "/servers.xml").exists()
                        && ApplicationAptoide.DEFAULTSTORENAME == null) {
                    try {

                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();

                        MyappHandler handler = new MyappHandler();

                        sp.parse(new File(LOCAL_PATH + "/servers.xml"), handler);
                        ArrayList<String> server = handler.getServers();
                        if (server.isEmpty()) {
                            serversFileIsEmpty = true;
                        } else {
                            getIntent().putExtra("newrepo", server);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                editor.putBoolean("firstrun", false);
                editor.putBoolean("orderByCategory", true);
                editor.commit();
            }

            if (getIntent().hasExtra("newrepo")) {
                ArrayList<String> repos = (ArrayList<String>) getIntent().getSerializableExtra("newrepo");
                for (final String uri2 : repos) {
                    View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout,
                            null);
                    Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
                    final AlertDialog addNewRepoDialog = dialogBuilder.create();
                    addNewRepoDialog.setTitle(getString(R.string.add_store));
                    addNewRepoDialog.setIcon(android.R.drawable.ic_menu_add);

                    TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
                    message.setText((getString(R.string.newrepo_alrt) + uri2 + " ?"));

                    addNewRepoDialog.setCancelable(false);
                    addNewRepoDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.yes),
                            new Dialog.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    dialogAddStore(uri2, null, null);
                                }
                            });
                    addNewRepoDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.no),
                            new Dialog.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int arg1) {
                                    dialog.cancel();
                                }
                            });
                    addNewRepoDialog.show();
                }
            } else if (db.getStores(false).getCount() == 0 && ApplicationAptoide.DEFAULTSTORENAME == null
                    && serversFileIsEmpty) {
                View simpleView = LayoutInflater.from(mContext).inflate(R.layout.dialog_simple_layout, null);
                Builder dialogBuilder = new AlertDialog.Builder(mContext).setView(simpleView);
                final AlertDialog addAppsRepoDialog = dialogBuilder.create();
                addAppsRepoDialog.setTitle(getString(R.string.add_store));
                addAppsRepoDialog.setIcon(android.R.drawable.ic_menu_add);
                TextView message = (TextView) simpleView.findViewById(R.id.dialog_message);
                message.setText(getString(R.string.myrepo_alrt) + "\n" + "http://apps.store.aptoide.com/");
                addAppsRepoDialog.setCancelable(false);
                addAppsRepoDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.yes),
                        new Dialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                dialogAddStore("http://apps.store.aptoide.com", null, null);
                            }
                        });
                addAppsRepoDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.no),
                        new Dialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.cancel();
                            }
                        });
                addAppsRepoDialog.show();
            }

            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        getUpdateParameters();
                        if (getPackageManager().getPackageInfo(getPackageName(), 0).versionCode < Integer
                                .parseInt(updateParams.get("versionCode"))) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    requestUpdateSelf();
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }

        featuredView = LayoutInflater.from(mContext).inflate(R.layout.page_featured, null);
        availableView = LayoutInflater.from(mContext).inflate(R.layout.page_available, null);
        updateView = LayoutInflater.from(mContext).inflate(R.layout.page_updates, null);
        banner = (LinearLayout) availableView.findViewById(R.id.banner);
        breadcrumbs = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.breadcrumb_container, null);
        installedView = new ListView(mContext);
        updatesListView = (ListView) updateView.findViewById(R.id.updates_list);

        availableListView = (ListView) availableView.findViewById(R.id.available_list);
        joinStores = (CheckBox) availableView.findViewById(R.id.join_stores);

        availableAdapter = new AvailableListAdapter(mContext, null,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        installedAdapter = new InstalledAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER,
                db);
        updatesAdapter = new UpdatesAdapter(mContext, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        pb = (TextView) availableView.findViewById(R.id.loading_pb);
        addStoreButton = availableView.findViewById(R.id.add_store);

        bannerStoreAvatar = (ImageView) banner.findViewById(R.id.banner_store_avatar);
        bannerStoreName = (TextView) banner.findViewById(R.id.banner_store_name);
        bannerStoreDescription = (AutoScaleTextView) banner.findViewById(R.id.banner_store_description);
    }
}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

public void handleRefreshMedia(final String path, boolean keepChecking, final int retries) {
    if (!keepChecking || retries <= 0) {
        refreshBookmarks();//from   www  .  j  a v  a  2  s  .c  om
        return;
    }
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            Logger.LogDebug("Check " + retries + " for " + path);
            try {
                StatFs sf = new StatFs(path);
                if (sf.getBlockCount() == 0)
                    throw new Exception("No blocks");
                showToast(getResources().getString(R.string.s_alert_new_media) + " " + getVolumeName(path)
                        + " @ "
                        + DialogHandler.formatSize((long) sf.getBlockSize() * (long) sf.getAvailableBlocks()));
                refreshBookmarks();
                if (mLastPath.getPath().equals(path))
                    goHome();
            } catch (Throwable e) {
                Logger.LogWarning("Couldn't read " + path);
                handleRefreshMedia(path, true, retries - 1); // retry again in 1/2 second
            }
        }
    }, 1000);
}