Android Open Source - Resonos-Android-Framework App Utils






From Project

Back to project page Resonos-Android-Framework.

License

The source code is released under:

Apache License

If you think the Android project Resonos-Android-Framework listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.resonos.apps.library.util;
//www .j  a v a2  s .  c  om
import java.io.File;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.webkit.CacheManager;
import android.widget.Toast;

import com.resonos.app.library.R;
import com.resonos.apps.library.App;
import com.resonos.apps.library.BaseFragment;
import com.resonos.apps.library.FragmentBaseActivity;

/**
 * This class is a group of functions that do common Android tasks such as:
 *   Welcome to the application tasks
 *   Intent-related tasks
 *   SharedPreference easy interaction
 * @author Chris
 *
 */
@SuppressWarnings("deprecation")
public class AppUtils {

  /** These constants are used to store preferences related to below functions */
  public static final String PREF_LOAD_COUNT = "loadedCount";
  public static final String PREF_LOADED = "loadedAtAll";
  public static final String PREF_VERSION = "loadedVersion";

  public static final String MARKET_INTENT_PREFIX = "market://details?id=";
  public static final String MARKET_URL_PREFIX = "http://play.google.com/store/apps/details?id=";
  
  public static Date getAppBuildDate(Context cx) {
    try {
      ApplicationInfo ai = cx.getPackageManager().getApplicationInfo(
          cx.getPackageName(), 0);
      ZipFile zf = new ZipFile(ai.sourceDir);
      ZipEntry ze = zf.getEntry("classes.dex");
      long time = ze.getTime();
      return new java.util.Date(time);
    } catch (Exception e) {
      return null;
    }

  }
  
  /**
   * Check if we should ask the user to rate the application 
   * Call this function once on loading the app, as it sets preferences behind the scenes
   * @param app context
   * @param ask the user every ___ loads
   * @return true if we should ask the user
   */
  public static boolean checkDisplayLoadMsg(Context cx, int count) {
    SharedPreferences settings = cx.getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    int loadedCount = settings.getInt(PREF_LOAD_COUNT, 0);
    loadedCount++;
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt(PREF_LOAD_COUNT, loadedCount);
    editor.commit();
    
    return (loadedCount == count);
  }
  
  /**
   * Remind the user to rate the app later -- resets the load count
   * @param app context
   */
  public static void remindMeLater(Context cx) {
    SharedPreferences settings = cx.getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt(PREF_LOAD_COUNT, 0);
    editor.commit();
  }

  /**
   * Returns true if this is the very first time the user has loaded the app
   * Call this function once on loading the app, as it sets preferences behind the scenes
   * @param app context
   * @return true if first load
   */
  public static boolean checkLoadedAtAll(Context cx) {
    SharedPreferences settings = cx.getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    boolean loaded = settings.getBoolean(PREF_LOADED, false);
    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean(PREF_LOADED, true);
    editor.commit();
    return loaded;
  }

  /**
   * Returns true if this is the first time the user loads a new version of the app
   * Call this function once on loading the app, as it sets preferences behind the scenes
   * Returns false if this is the first time the user loaded the app at all,
   * as it is not really a new version to them.
   * Call this function once on loading the app, as it sets preferences behind the scenes
   * @param app object
   * @return true if new version to user
   */
  public static boolean checkNewVersionFirstLoad(App app) {
    SharedPreferences settings = app.getContext()
        .getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    String version = settings.getString(PREF_VERSION, app.mAppInfo._versionID);
    if (!version.equals(app.getVersionID())) {
      SharedPreferences.Editor editor = settings.edit();
      editor.putString(PREF_VERSION, app.getVersionID());
      editor.commit();
      return true;
    } else
      return false;
  }

  /**
   * Use this function to get a drawable ready to modify from a resource
   * @param cx : the context
   * @param resId : the resource id
   * @return a mutable Drawable object
   */
  public static Drawable getMutableDrawable(Context cx, int resId) {
    Bitmap immutableBitmap = BitmapFactory.decodeResource(cx.getResources(), resId);
    Bitmap mutableBitmap = immutableBitmap.copy(Bitmap.Config.ARGB_8888,
        true);
//    immutableBitmap.recycle();
//    immutableBitmap = null;
    Drawable d = new BitmapDrawable(cx.getResources(), mutableBitmap);
    return d;
  }
  
  /**
   * Easily get a SavedPreferences integer
   * @param app object
   * @param key
   * @param default value
   * @return the integer, or default value if the key was not found
   */
  public static int getSavedInt(App app, String key, int def) {
    SharedPreferences settings = app.getContext()
        .getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    return settings.getInt(key, def);
  }
  
  /**
   * Easily set a SavedPreferences integer
   * @param app object
   * @param key
   * @param value to save
   */
  public static void setSavedInt(App app, String key, int val) {
    SharedPreferences settings = app.getContext()
        .getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    settings.edit().putInt(key, val).commit();
  }
  
  /**
   * Easily get a SavedPreferences boolean
   * @param app object
   * @param key
   * @param default value
   * @return the integer, or default value if the key was not found
   */
  public static boolean getSavedBoolean(App app, String key, boolean def) {
    SharedPreferences settings = app.getContext()
        .getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    return settings.getBoolean(key, def);
  }
  
  /**
   * Easily set a SavedPreferences boolean
   * @param app object
   * @param key
   * @param value to save
   */
  public static void setSavedBoolean(App app, String key, boolean val) {
    SharedPreferences settings = app.getContext()
        .getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    settings.edit().putBoolean(key, val).commit();
  }
  
  /**
   * Easily get a SavedPreferences String
   * @param app object
   * @param key
   * @param default value
   * @return the integer, or default value if the key was not found
   */
  public static String getSavedString(App app, String key, String def) {
    SharedPreferences settings = app.getContext()
        .getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    return settings.getString(key, def);
  }
  
  /**
   * Easily set a SavedPreferences boolean
   * @param app object
   * @param key
   * @param value to save
   */
  public static void setSavedString(App app, String key, String val) {
    SharedPreferences settings = app.getContext()
        .getSharedPreferences(App.GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    settings.edit().putString(key, val).commit();
  }

  /**
   * Saves a fragment type in a bundle.
   * @param a : the Fragment activity
   * @param outState : the saved bundle
   * @param owner : the owner of the key
   * @param key : the key the fragment should be saved in
   */
  public static void putFragment(FragmentBaseActivity a, Bundle outState, Object owner,
      String key, BaseFragment f) {
    outState.putString(key, (f == null) ? null : f.getTag());
    M.log("AppUtils", owner.toString() + " putFragment: " + key + " - " + ((f == null) ? "_null" : f.getTag()));
    
//    alternative based on fragment manager API -- does not work as expected for our case
//    if (f != null)
//      a.getSupportFragmentManager().putFragment(outState,
//          AppUtils.createBundleKey(owner, key), f);
  }

  /**
   * Retrieves a fragment type matching one saved in a bundle.
   * @param a : the Fragment activity
   * @param inState : the saved bundle
   * @param owner : the owner of the key
   * @param key : the key the fragment is saved in
   * @return The fragment, if found, or null if it does not exist or the key was not found.
   */
  public static BaseFragment getFragment(FragmentBaseActivity a, Bundle inState, Object owner,
      String key) {
    String tag = inState.getString(key);
    if (tag != null) {
      Fragment f = a.getSupportFragmentManager().findFragmentByTag(tag);
      if (f instanceof BaseFragment) {
        M.log("AppUtils", owner.toString() + " getFragment: " + key + " - " + "found " + f.toString());
        return (BaseFragment)f;
      }
    }
    M.log("AppUtils", owner.toString() + " getFragment: " + key + " - " + "found nothing");
    return null;

//    alternative based on fragment manager API -- does not work as expected for our case
//    Fragment f = a.getSupportFragmentManager().getFragment(inState,
//        AppUtils.createBundleKey(owner, key));
//    return (BaseFragment)f;
  }
  
  /**
   * Launch an intent to send an email to developer asking for help
   * @param app object
   */
  public static void launchHelpEmail(App app) {
      Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);  
      emailIntent.setType("plain/text");  
      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{app.mAppInfo.contactEmailHelp});  
      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Help: " + app.getAppName() + " " + app.getVersionID());  
      emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, app.getContext().getString(R.string.help_email));  
      app.getContext().startActivity(Intent.createChooser(emailIntent, app.getContext().getString(R.string.send_email)));
  }

  /**
   * Launch the Google Play Market to this app's page
     * toasts if no market
   * @param app object
   */
    public static void launchMarketThisApp(App app) {
      launchMarket(app.getActivity(), app.mAppInfo._packageName);
  }

    /**
     * Launch the Google Play Market to this app's pro package
     * (which could be this app if it is upgraded)
     * toasts if no market
     * Does nothing if no pro package is set.
     * @param app
     */
    public static void launchMarketPro(App app) {
      if (app.mAppInfo.packageProName != null)
      launchMarket(app.getActivity(), app.mAppInfo.packageProName);
  }

    /**
     * Launches the GooglePlayMarket to an arbitrary package.
     * toasts if no market
     * @param app object
     * @param package name
     */
  public static void launchMarket(Activity cx, String packageName) {
    try {
      boolean doit = true;
      if (cx != null)
        doit = !cx.isFinishing();
        if (doit) {
            String url = MARKET_INTENT_PREFIX + packageName;
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            cx.startActivity(i);
        }
    } catch (Exception e) {
      try {
            String url = MARKET_URL_PREFIX + packageName;
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            cx.startActivity(i);
      } catch (Exception x) {
        Toast.makeText(cx, R.string.txt_no_market, Toast.LENGTH_SHORT).show();
      }
    }
  }

    /**
     * Launches the browser to an arbitrary page.
     * toasts if no browser
     * @param app object
     * @param URL
     */
  public static void loadPage(App app, String url) {
    try {
          Intent i = new Intent(Intent.ACTION_VIEW);
          i.setData(Uri.parse(url));
          app.getContext().startActivity(i);
    } catch (Exception x) {
      app.toast(R.string.txt_no_browser, false);
    }
  }

  /**
   * Try to avoid the assortment of guaranteed crashes that comes along
   *  with even using a WebView in Android
   * @param context
   */
  public static void clearCache(final Context context) {
      // avoid db corruption exceptions by clearing the webview database
    try {
      context.deleteDatabase("webview.db");
      context.deleteDatabase("webviewCache.db");
        clearCacheFolder(context.getCacheDir(), 0);
    } catch (Throwable e) {
      //
    }
    
      // now attempt to disable it completely
    try {
      Method m = CacheManager.class.getDeclaredMethod("setCacheDisabled",
          boolean.class);
      m.setAccessible(true);
      m.invoke(null, true);
    } catch (Throwable e) {
      //
    }
  }
  
  /**
   * Clear recursively a cache folder
   *  from: http://stackoverflow.com/questions/2465432/android-webview-completely-clear-the-cache
   * @param dir : the folder
   * @param numDays : number of days to keep, (eg 0 to delete all)
   * @return number of delete files
   */
  private static int clearCacheFolder(final File dir, final int numDays) {
    int deletedFiles = 0;
    if (dir != null && dir.isDirectory()) {
      try {
        for (File child : dir.listFiles()) {

          // first delete subdirectories recursively
          if (child.isDirectory()) {
            deletedFiles += clearCacheFolder(child, numDays);
          }

          // then delete the files and subdirectories in this dir
          // only empty directories can be deleted, so subdirs have
          // been done first
          if (child.lastModified() < new Date().getTime() - numDays
              * DateUtils.DAY_IN_MILLIS) {
            if (child.delete()) {
              deletedFiles++;
            }
          }
        }
      } catch (Exception e) {
        //
      }
    }
    return deletedFiles;
  }
}




Java Source Code List

com.resonos.apps.library.Action.java
com.resonos.apps.library.AlertFragment.java
com.resonos.apps.library.App.java
com.resonos.apps.library.BaseFragment.java
com.resonos.apps.library.FragmentBaseActivity.java
com.resonos.apps.library.file.AltAndroidFileHandle.java
com.resonos.apps.library.file.AltAndroidFiles.java
com.resonos.apps.library.file.AltFileHandle.java
com.resonos.apps.library.file.FileCache.java
com.resonos.apps.library.media.AudioVisualizer.java
com.resonos.apps.library.media.BitmapMemoryCache.java
com.resonos.apps.library.media.HueColorFilter.java
com.resonos.apps.library.media.ImageLoader.java
com.resonos.apps.library.media.MediaScannerNotifier.java
com.resonos.apps.library.model.Coord.java
com.resonos.apps.library.model.ImmutableCoord.java
com.resonos.apps.library.tabviewpager.CustomViewPager.java
com.resonos.apps.library.tabviewpager.PageIndicator.java
com.resonos.apps.library.tabviewpager.TabPageIndicator.java
com.resonos.apps.library.tabviewpager.TabViewPagerAdapter.java
com.resonos.apps.library.tabviewpager.TabViewPagerFragment.java
com.resonos.apps.library.tabviewpager.TitleProvider.java
com.resonos.apps.library.util.AppUtils.java
com.resonos.apps.library.util.ErrorReporter.java
com.resonos.apps.library.util.LifecycleTaskQueue.java
com.resonos.apps.library.util.M.java
com.resonos.apps.library.util.NetworkClient.java
com.resonos.apps.library.util.NetworkRequest.java
com.resonos.apps.library.util.ParameterList.java
com.resonos.apps.library.util.SensorReader.java
com.resonos.apps.library.util.TouchViewWorker.java
com.resonos.apps.library.util.ViewServer.java
com.resonos.apps.library.widget.DashboardLayout.java
com.resonos.apps.library.widget.FormBuilder.java
com.resonos.apps.library.widget.FormElement.java
com.resonos.apps.library.widget.ListFormBuilder.java
com.resonos.apps.library.widget.PopupWindows3D.java
com.resonos.apps.library.widget.QuickAction3D.java
com.resonos.apps.library.widget.RangeSeekBar.java
com.resonos.apps.library.widget.SeekBar.java
com.resonos.apps.library.widget.ToolBarButton.java
com.resonos.apps.library.widget.ToolBar.java