Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Monday, January 19, 2015

how to make a application wide locale change in Andorid

Today, While testing on Arabic language I found that app cannot query data from the database due to Arabic numeral system being different from English. So, I decided to enforce English on whole language

In the Manifest,

 <application
        android:name="MyApplication" >

Code:

public class MyApplication extends Application {
  @Override
  public void onCreate()
  {
    switchLocale()
    super.onCreate();
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      switchLocale();
  }
}
public static void switchLocale(Context context) {
    try {
          Locale currentLocale = Locale.getDefault();
       
          if(currentLocale != null) {
              if (currentLocale != Locale.US || currentLocale != Locale.UK) {
                  final String languageToLoad  = "en";
                  Locale locale = new Locale(languageToLoad);
                  Locale.setDefault(locale);
               
                  Configuration config = new Configuration();
                  config.locale = locale;
                  context.getResources().updateConfiguration(config, null);
              }
          }
      } catch (Throwable e) {
       
      }
}

Wednesday, July 30, 2014

How to check whether device is running CyanogenMod in Android

Today, I wanted to know how to detect whether device is running CyanogenMod. System.getProperty("os.version") used to return cyanogenmod however it is not the case when i checked it today. CyanogenMod. System.getProperty("os.version")  was returning something like 3.0.64-CM-g9d16c8a. So I wrote this function. Hope it will be use full for someone else.

private boolean isCyanogenMod(PackageManager pm) {
    boolean isCyanogenMod = false;
    String version = System.getProperty("os.version");
    BufferedReader reader = null;

    try {
        if (version.contains("cyanogenmod") || pm.hasSystemFeature("com.cyanogenmod.android")) {
            isCyanogenMod = true;
        }
        else {                
            // This does not require root
            reader = new BufferedReader(new FileReader("/proc/version"), 256);
            version = reader.readLine();

            if (version.contains("cyanogenmod")) {
                isCyanogenMod = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        if(reader != null) {
            try { reader.close(); } catch (IOException e) { }
        }
    }

    return isCyanogenMod;
}



Monday, May 12, 2014

Android LocalServerSocket cannot handle more then 1024 connects/disconnects

For last couple of days I have been trying to fix one serious issue in my app. In Android 4.4.2 a client cannot connect /disconnect to server (created using LocalServerSocket Domain UNIX Socket)  more than 1024 times. How fucked up is that ?

I have uploaded my demo code here http://speedy.sh/NBSjr/SocketIssue.zip

I have posted questions on StackOverflow here http://stackoverflow.com/questions/23559827/emfile-too-many-open-files-error-while-connecting-to-localserversocket

and Google https://code.google.com/p/android/issues/detail?id=69594

Still got nothing!.

After few hours of pulling my hair out, I remembered Jackpal terminal emulator had some code to close the file descriptor. So I decided to take a look there.

https://github.com/jackpal/Android-Terminal-Emulator/blob/master/jni/termExec.cpp

If you pass the client socket file descriptor to his close function. it closes the connection. However it leaves a error on LogCat.

Please let me know if someone found a better solution.



Saturday, December 7, 2013

FileNameMap getContentTypeFor returns null Android

I have been using this piece of code for a long time to get the mime type of the file 

FileNameMap fileNameMap = URLConnection.getFileNameMap();
String type = fileNameMap.getContentTypeFor(fileName);

Today, I found out that sometimes it returns null and throws an null error exception. Since there is no other option I had to come up with a class.

import java.io.File;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class MimeTypes {
    private static final Map<String, String> EXT2MIME = new HashMap<String, String>();
    private static final Map<String, String> MIME2EXT = new HashMap<String, String>();
    private MimeTypes() {
    }
    static {
        // extension to MIME type
        EXT2MIME.put("", "application/octet-stream");
        EXT2MIME.put("ai", "application/postscript");
        EXT2MIME.put("aif", "audio/x-aiff");
        EXT2MIME.put("aifc", "audio/x-aiff");
        EXT2MIME.put("aiff", "audio/x-aiff");
        EXT2MIME.put("asf", "video/x-ms-asf");
        EXT2MIME.put("asr", "video/x-ms-asf");
        EXT2MIME.put("asx", "video/x-ms-asf");
        EXT2MIME.put("au", "audio/basic");
        EXT2MIME.put("avi", "video/x-msvideo");
        EXT2MIME.put("axs", "application/olescript");
        EXT2MIME.put("bas", "text/plain");
        EXT2MIME.put("bmp", "image/bmp");
        EXT2MIME.put("c", "text/plain");
        EXT2MIME.put("cat", "application/vnd.ms-pkiseccat");
        EXT2MIME.put("cdf", "application/x-cdf");
        EXT2MIME.put("cer", "application/x-x509-ca-cert");
        EXT2MIME.put("class", "application/java-vm");
        EXT2MIME.put("clp", "application/x-msclip");
        EXT2MIME.put("cmx", "image/x-cmx");
        EXT2MIME.put("cod", "image/cis-cod");
        EXT2MIME.put("cpio", "application/x-cpio");
        EXT2MIME.put("crd", "application/x-mscardfile");
        EXT2MIME.put("crl", "application/pkix-crl");
        EXT2MIME.put("crt", "application/x-x509-ca-cert");
        EXT2MIME.put("csh", "application/x-csh");
        EXT2MIME.put("css", "text/css");
        EXT2MIME.put("dll", "application/x-msdownload");
        EXT2MIME.put("doc", "application/msword");
        EXT2MIME.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        EXT2MIME.put("doct", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
        EXT2MIME.put("dot", "application/msword");
        EXT2MIME.put("dvi", "application/x-dvi");
        EXT2MIME.put("dxr", "application/x-director");
        EXT2MIME.put("eps", "application/postscript");
        EXT2MIME.put("epub", "application/epub+zip");
        EXT2MIME.put("etx", "text/x-setext");
        EXT2MIME.put("evy", "application/envoy");
        EXT2MIME.put("flac", "audio/flac");
        EXT2MIME.put("fif", "application/fractals");
        EXT2MIME.put("flr", "x-world/x-vrml");
        EXT2MIME.put("gif", "image/gif");
        EXT2MIME.put("gtar", "application/x-gtar");
        EXT2MIME.put("gz", "application/x-gzip");
        EXT2MIME.put("h", "text/plain");
        EXT2MIME.put("hdf", "application/x-hdf");
        EXT2MIME.put("hlp", "application/winhlp");
        EXT2MIME.put("hqx", "application/mac-binhex40");
        EXT2MIME.put("hta", "application/hta");
        EXT2MIME.put("htc", "text/x-component");
        EXT2MIME.put("htm", "text/html");
        EXT2MIME.put("html", "text/html");
        EXT2MIME.put("htt", "text/webviewhtml");
        EXT2MIME.put("ico", "image/x-icon");
        EXT2MIME.put("ief", "image/ief");
        EXT2MIME.put("iii", "application/x-iphone");
        EXT2MIME.put("isp", "application/x-internet-signup");
        EXT2MIME.put("jar", "application/java-archive");
        EXT2MIME.put("jfif", "image/pipeg");
        EXT2MIME.put("jpe", "image/jpeg");
        EXT2MIME.put("jpeg", "image/jpeg");
        EXT2MIME.put("jpg", "image/jpeg");
        EXT2MIME.put("js", "application/x-javascript");
        EXT2MIME.put("json", "application/json");
        EXT2MIME.put("latex", "application/x-latex");
        EXT2MIME.put("lsf", "video/x-la-asf");
        EXT2MIME.put("lsx", "video/x-la-asf");
        EXT2MIME.put("m3u", "audio/x-mpegurl");
        EXT2MIME.put("man", "application/x-troff-man");
        EXT2MIME.put("mdb", "application/x-msaccess");
        EXT2MIME.put("me", "application/x-troff-me");
        EXT2MIME.put("mhtv", "message/rfc822");
        EXT2MIME.put("mhtml", "message/rfc822");
        EXT2MIME.put("mid", "audio/mid");
        EXT2MIME.put("mov", "video/quicktime");
        EXT2MIME.put("movie", "video/x-sgi-movie");
        EXT2MIME.put("mp2", "video/mpeg");
        EXT2MIME.put("mp3", "audio/mpeg");
        EXT2MIME.put("mpa", "video/mpeg");
        EXT2MIME.put("mpe", "video/mpegv");
        EXT2MIME.put("mpeg", "video/mpeg");
        EXT2MIME.put("mpg", "video/mpegv");
        EXT2MIME.put("mpp", "application/vnd.ms-project");
        EXT2MIME.put("mpv2", "video/mpeg");
        EXT2MIME.put("ms", "application/x-troff-ms");
        EXT2MIME.put("mvb", "application/x-msmediaview");
        EXT2MIME.put("nws", "message/rfc822");
        EXT2MIME.put("oda", "application/oda");
        EXT2MIME.put("odb", "application/vnd.oasis.opendocument.database");
        EXT2MIME.put("odc", "application/vnd.oasis.opendocument.chart");
        EXT2MIME.put("odf", "application/vnd.oasis.opendocument.formula");
        EXT2MIME.put("odft", "application/vnd.oasis.opendocument.formula-template");
        EXT2MIME.put("odg", "application/vnd.oasis.opendocument.graphics");
        EXT2MIME.put("odi", "application/vnd.oasis.opendocument.image");
        EXT2MIME.put("odm", "application/vnd.oasis.opendocument.text-master");
        EXT2MIME.put("odp", "application/vnd.oasis.opendocument.presentation");
        EXT2MIME.put("ods", "application/vnd.oasis.opendocument.spreadsheet");
        EXT2MIME.put("odt", "application/vnd.oasis.opendocument.text");
        EXT2MIME.put("ogg", "audio/ogg");
        EXT2MIME.put("ogv", "video/ogg");
        EXT2MIME.put("otc", "application/vnd.oasis.opendocument.chart-template");
        EXT2MIME.put("otg", "application/vnd.oasis.opendocument.graphics-template");
        EXT2MIME.put("oth", "application/vnd.oasis.opendocument.text-web");
        EXT2MIME.put("oti", "application/vnd.oasis.opendocument.image-template");
        EXT2MIME.put("otp", "application/vnd.oasis.opendocument.presentation-template");
        EXT2MIME.put("ots", "application/vnd.oasis.opendocument.spreadsheet-template");
        EXT2MIME.put("ott", "application/vnd.oasis.opendocument.text-template");
        EXT2MIME.put("p10", "application/pkcs10");
        EXT2MIME.put("p12", "application/x-pkcs12v");
        EXT2MIME.put("p7b", "application/x-pkcs7-certificates");
        EXT2MIME.put("p7c", "application/x-pkcs7-mime");
        EXT2MIME.put("p7m", "application/x-pkcs7-mime");
        EXT2MIME.put("p7r", "application/x-pkcs7-certreqresp");
        EXT2MIME.put("p7s", "application/x-pkcs7-signature");
        EXT2MIME.put("pbm", "image/x-portable-bitmap");
        EXT2MIME.put("pdf", "application/pdf");
        EXT2MIME.put("pfx", "application/x-pkcs12");
        EXT2MIME.put("pgm", "image/x-portable-graymap");
        EXT2MIME.put("vpko", "application/ynd.ms-pkipko");
        EXT2MIME.put("pma", "application/x-perfmon");
        EXT2MIME.put("pmc", "application/x-perfmon");
        EXT2MIME.put("pml", "application/x-perfmon");
        EXT2MIME.put("pmr", "application/x-perfmon");
        EXT2MIME.put("pmw", "application/x-perfmon");
        EXT2MIME.put("png", "image/png");
        EXT2MIME.put("pnm", "image/x-portable-anymap");
        EXT2MIME.put("pot", "application/vnd.ms-powerpoint");
        EXT2MIME.put("ppm", "image/x-portable-pixmap");
        EXT2MIME.put("pps", "application/vnd.ms-powerpoint");
        EXT2MIME.put("ppt", "application/vnd.ms-powerpoint");
        EXT2MIME.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
        EXT2MIME.put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
        EXT2MIME.put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
        EXT2MIME.put("prf", "application/pics-rules");
        EXT2MIME.put("ps", "application/postscript");
        EXT2MIME.put("pub", "application/x-mspublisher");
        EXT2MIME.put("qt", "video/quicktime");
        EXT2MIME.put("ra", "audio/x-pn-realaudio");
        EXT2MIME.put("ram", "audio/x-pn-realaudio");
        EXT2MIME.put("ras", "image/x-cmu-raster");
        EXT2MIME.put("rgb", "image/x-rgb");
        EXT2MIME.put("rmi", "audio/mid");
        EXT2MIME.put("roff", "application/x-troff");
        EXT2MIME.put("rtf", "application/rtf");
        EXT2MIME.put("rtx", "text/richtext");
        EXT2MIME.put("ser", "application/java-serialized-object");
        EXT2MIME.put("scd", "application/x-msschedule");
        EXT2MIME.put("sct", "text/scriptlet");
        EXT2MIME.put("sh", "application/x-sh");
        EXT2MIME.put("shar", "application/x-shar");
        EXT2MIME.put("sit", "application/x-stuffit");
        EXT2MIME.put("snd", "audio/basic");
        EXT2MIME.put("spc", "application/x-pkcs7-certificates");
        EXT2MIME.put("spl", "application/futuresplash");
        EXT2MIME.put("src", "application/x-wais-source");
        EXT2MIME.put("sst", "application/vnd.ms-pkicertstore");
        EXT2MIME.put("stl", "application/vnd.ms-pkistl");
        EXT2MIME.put("stm", "text/html");
        EXT2MIME.put("svg", "image/svg+xml");
        EXT2MIME.put("swf", "application/x-shockwave-flash");
        EXT2MIME.put("t", "application/x-troff");
        EXT2MIME.put("tar", "application/x-tar");
        EXT2MIME.put("tcl", "application/x-tcl");
        EXT2MIME.put("tex", "application/x-tex");
        EXT2MIME.put("texi", "application/x-texinfo");
        EXT2MIME.put("texinfo", "application/x-texinfo");
        EXT2MIME.put("tgz", "application/x-compressed");
        EXT2MIME.put("tif", "image/tiff");
        EXT2MIME.put("tiff", "image/tiff");
        EXT2MIME.put("tr", "application/x-troff");
        EXT2MIME.put("trm", "application/x-msterminal");
        EXT2MIME.put("tsv", "text/tab-separated-values");
        EXT2MIME.put("txt", "text/plain");
        EXT2MIME.put("uls", "text/iuls");
        EXT2MIME.put("ustar", "application/x-ustar");
        EXT2MIME.put("vcf", "text/x-vcard");
        EXT2MIME.put("vrml", "x-world/x-vrml");
        EXT2MIME.put("wav", "audio/x-wav");
        EXT2MIME.put("wcm", "application/vnd.ms-works");
        EXT2MIME.put("wdb", "application/vnd.ms-works");
        EXT2MIME.put("wmf", "application/x-msmetafile");
        EXT2MIME.put("wps", "application/vnd.ms-works");
        EXT2MIME.put("wri", "application/x-mswrite");
        EXT2MIME.put("wrl", "x-world/x-vrml");
        EXT2MIME.put("wrz", "x-world/x-vrml");
        EXT2MIME.put("xaf", "x-world/x-vrml");
        EXT2MIME.put("xbm", "image/x-xbitmap");
        EXT2MIME.put("xla", "application/vnd.ms-excel");
        EXT2MIME.put("xlc", "application/vnd.ms-excel");
        EXT2MIME.put("xlm", "application/vnd.ms-excel");
        EXT2MIME.put("xls", "application/vnd.ms-excel");
        EXT2MIME.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        EXT2MIME.put("xlt", "application/vnd.ms-excel");
        EXT2MIME.put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
        EXT2MIME.put("xlw", "application/vnd.ms-excel");
        EXT2MIME.put("xml", "text/xml");
        EXT2MIME.put("xof", "x-world/x-vrml");
        EXT2MIME.put("xpm", "image/x-xpixmap");
        EXT2MIME.put("xwd", "image/x-xwindowdump");
        EXT2MIME.put("z", "application/x-compress");
        EXT2MIME.put("zip", "application/zip");
        // MIME type to extension
        MIME2EXT.put("application/octet-stream", "");
        MIME2EXT.put("application/envoy", "evy");
        MIME2EXT.put("application/epub+zip", "epub");
        MIME2EXT.put("application/fractals", "fif");
        MIME2EXT.put("application/futuresplash", "spl");
        MIME2EXT.put("application/hta", "hta");
        MIME2EXT.put("application/java-archive", "jar");
        MIME2EXT.put("application/java-serialized-object", "ser");
        MIME2EXT.put("application/java-vm", "class");
        MIME2EXT.put("application/javascript", "js");
        MIME2EXT.put("application/json", "json");
        MIME2EXT.put("application/mac-binhex40", "hqx");
        MIME2EXT.put("application/msword", "doc");
        MIME2EXT.put("application/oda", "oda");
        MIME2EXT.put("application/olescript", "axs");
        MIME2EXT.put("application/pdf", "pdf");
        MIME2EXT.put("application/pics-rules", "prf");
        MIME2EXT.put("application/pkcs10", "p10");
        MIME2EXT.put("application/pkix-crl", "crl");
        MIME2EXT.put("application/postscript", "ps");
        MIME2EXT.put("application/rtf", "rtf");
        MIME2EXT.put("application/vnd.ms-excel", "xls");
        MIME2EXT.put("application/vnd.ms-pkicertstore", "sst");
        MIME2EXT.put("application/vnd.ms-pkiseccat", "cat");
        MIME2EXT.put("application/vnd.ms-pkistl", "stl");
        MIME2EXT.put("application/vnd.ms-powerpoint", "ppt");
        MIME2EXT.put("application/vnd.ms-project", "mpp");
        MIME2EXT.put("application/vnd.ms-works", "wps");
        MIME2EXT.put("application/vnd.oasis.opendocument.chart", "odc");
        MIME2EXT.put("application/vnd.oasis.opendocument.chart-template", "otc");
        MIME2EXT.put("application/vnd.oasis.opendocument.database", "odb");
        MIME2EXT.put("application/vnd.oasis.opendocument.formula", "odf");
        MIME2EXT.put("application/vnd.oasis.opendocument.formula-template", "odft");
        MIME2EXT.put("application/vnd.oasis.opendocument.graphics", "odg");
        MIME2EXT.put("application/vnd.oasis.opendocument.graphics-template", "otg");
        MIME2EXT.put("application/vnd.oasis.opendocument.image", "odi");
        MIME2EXT.put("application/vnd.oasis.opendocument.image-template", "oti");
        MIME2EXT.put("application/vnd.oasis.opendocument.presentation", "odp");
        MIME2EXT.put("application/vnd.oasis.opendocument.presentation-template", "otp");
        MIME2EXT.put("application/vnd.oasis.opendocument.spreadsheet", "ods");
        MIME2EXT.put("application/vnd.oasis.opendocument.spreadsheet-template", "ots");
        MIME2EXT.put("application/vnd.oasis.opendocument.text", "odt");
        MIME2EXT.put("application/vnd.oasis.opendocument.text-master", "odm");
        MIME2EXT.put("application/vnd.oasis.opendocument.text-template", "ott");
        MIME2EXT.put("application/vnd.oasis.opendocument.text-web", "oth");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.presentationml.slideshow", "ppsx");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.presentationml.template", "potx");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.spreadsheetml.template", "xltx");
        MIME2EXT.put("application/winhlp", "hlp");
        MIME2EXT.put("application/x-cdf", "cdf");
        MIME2EXT.put("application/x-compress", "z");
        MIME2EXT.put("application/x-compressed", "tgz");
        MIME2EXT.put("application/x-cpio", "cpio");
        MIME2EXT.put("application/x-csh", "csh");
        MIME2EXT.put("application/x-director", "dxr");
        MIME2EXT.put("application/x-dvi", "dvi");
        MIME2EXT.put("application/x-gtar", "gtar");
        MIME2EXT.put("application/x-gzip", "gz");
        MIME2EXT.put("application/x-hdf", "hdf");
        MIME2EXT.put("application/x-internet-signup", "isp");
        MIME2EXT.put("application/x-iphone", "iii");
        MIME2EXT.put("application/x-javascript", "js");
        MIME2EXT.put("application/x-latex", "latex");
        MIME2EXT.put("application/x-msaccess", "mdb");
        MIME2EXT.put("application/x-mscardfile", "crd");
        MIME2EXT.put("application/x-msclip", "clp");
        MIME2EXT.put("application/x-msdownload", "dll");
        MIME2EXT.put("application/x-msmediaview", "mvb");
        MIME2EXT.put("application/x-msmetafile", "wmf");
        MIME2EXT.put("application/x-mspublisher", "pub");
        MIME2EXT.put("application/x-msschedule", "scd");
        MIME2EXT.put("application/x-msterminal", "trm");
        MIME2EXT.put("application/x-mswrite", "wri");
        MIME2EXT.put("application/x-perfmon", "pmw");
        MIME2EXT.put("application/x-pkcs12", "pfx");
        MIME2EXT.put("application/x-pkcs12v", "p12");
        MIME2EXT.put("application/x-pkcs7-certificates", "p7b");
        MIME2EXT.put("application/x-pkcs7-certificates", "spc");
        MIME2EXT.put("application/x-pkcs7-certreqresp", "p7r");
        MIME2EXT.put("application/x-pkcs7-mime", "p7m");
        MIME2EXT.put("application/x-pkcs7-signature", "p7s");
        MIME2EXT.put("application/x-sh", "sh");
        MIME2EXT.put("application/x-shar", "shar");
        MIME2EXT.put("application/x-shockwave-flash", "swf");
        MIME2EXT.put("application/x-stuffit", "sit");
        MIME2EXT.put("application/x-tar", "tar");
        MIME2EXT.put("application/x-tcl", "tcl");
        MIME2EXT.put("application/x-tex", "tex");
        MIME2EXT.put("application/x-texinfo", "texinfo");
        MIME2EXT.put("application/x-troff-man", "man");
        MIME2EXT.put("application/x-troff-me", "me");
        MIME2EXT.put("application/x-troff-ms", "ms");
        MIME2EXT.put("application/x-troff", "tr");
        MIME2EXT.put("application/x-ustar", "ustar");
        MIME2EXT.put("application/x-wais-source", "src");
        MIME2EXT.put("application/x-x509-ca-cert", "cer");
        MIME2EXT.put("application/ynd.ms-pkipko", "vpko");
        MIME2EXT.put("application/zip", "zip");
        MIME2EXT.put("audio/basic", "snd");
        MIME2EXT.put("audio/flac", "flac");
        MIME2EXT.put("audio/mid", "mid");
        MIME2EXT.put("audio/mpeg", "mp3");
        MIME2EXT.put("audio/ogg", "ogg");
        MIME2EXT.put("audio/x-aiff", "aif");
        MIME2EXT.put("audio/x-mpegurl", "m3u");
        MIME2EXT.put("audio/x-pn-realaudio", "ram");
        MIME2EXT.put("audio/x-wav", "wav");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.wordprocessingml.template", "doct");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");
        MIME2EXT.put("image/bmp", "bmp");
        MIME2EXT.put("image/cis-cod", "cod");
        MIME2EXT.put("image/gif", "gif");
        MIME2EXT.put("image/ief", "ief");
        MIME2EXT.put("image/jpeg", "jpeg");
        MIME2EXT.put("image/pipeg", "jfif");
        MIME2EXT.put("image/png", "png");
        MIME2EXT.put("image/svg+xml", "svg");
        MIME2EXT.put("image/tiff", "tiff");
        MIME2EXT.put("image/x-cmu-raster", "ras");
        MIME2EXT.put("image/x-cmx", "cmx");
        MIME2EXT.put("image/x-icon", "ico");
        MIME2EXT.put("image/x-portable-anymap", "pnm");
        MIME2EXT.put("image/x-portable-bitmap", "pbm");
        MIME2EXT.put("image/x-portable-graymap", "pgm");
        MIME2EXT.put("image/x-portable-pixmap", "ppm");
        MIME2EXT.put("image/x-rgb", "rgb");
        MIME2EXT.put("image/x-xbitmap", "xbm");
        MIME2EXT.put("image/x-xpixmap", "xpm");
        MIME2EXT.put("image/x-xwindowdump", "xwd");
        MIME2EXT.put("message/rfc822", "mhtml");
        MIME2EXT.put("text/css", "css");
        MIME2EXT.put("text/html", "html");
        MIME2EXT.put("text/iuls", "uls");
        MIME2EXT.put("text/plain", "txt");
        MIME2EXT.put("text/richtext", "rtx");
        MIME2EXT.put("text/scriptlet", "sct");
        MIME2EXT.put("text/tab-separated-values", "tsv");
        MIME2EXT.put("text/webviewhtml", "htt");
        MIME2EXT.put("text/x-component", "htc");
        MIME2EXT.put("text/x-setext", "etx");
        MIME2EXT.put("text/x-vcard", "vcf");
        MIME2EXT.put("text/xml", "xml");
        MIME2EXT.put("video/mpeg", "mpeg");
        MIME2EXT.put("video/mpegv", "mpe");
        MIME2EXT.put("video/ogg", "ogv");
        MIME2EXT.put("video/quicktime", "mov");
        MIME2EXT.put("video/quicktime", "qt");
        MIME2EXT.put("video/x-la-asf", "lsf");
        MIME2EXT.put("video/x-la-asf", "lsx");
        MIME2EXT.put("video/x-ms-asf", "asf");
        MIME2EXT.put("video/x-msvideo", "avi");
        MIME2EXT.put("video/x-sgi-movie", "movie");
        MIME2EXT.put("x-world/x-vrml", "vrml");
    }
    /**
     * Returns the MIME type for file extension.
     */
    public static String getMIMEType(String ext) {
        if (ext == null) {
            return EXT2MIME.get("");
        }
        int x = ext.lastIndexOf('.');
        if (x > -1) {
            ext = ext.substring(x + 1);
        }
        String mime = EXT2MIME.get(ext.toLowerCase());
        if (mime == null) {
            mime = URLConnection.getFileNameMap().getContentTypeFor("x." + ext);
        }
        if (mime == null) {
            mime = EXT2MIME.get("");
        }
        return mime;
    }
    /**
     * Returns the MIME type for a file.
     */
    public static String getMIMEType(File file) {
        if (file == null) {
            return getMIMEType("");
        }
        return getMIMEType(file.getName());
    }
    /**
     * Guesses a extension from a MIME type.
     */
    public static String getExtension(String mimeType) {
        if (mimeType == null) {
            return "";
        }
        int x = mimeType.indexOf(';');
        if (x > -1) {
            mimeType = mimeType.substring(0, x);
        }
        mimeType = mimeType.trim().toLowerCase(Locale.ENGLISH);
        String extension = MIME2EXT.get(mimeType);
        return ((extension == null || extension.length() == 0) ? "" : "." + extension);
    }
}

Wednesday, February 20, 2013

How to show/prompt login every time user returns or open the application

Today, I wanted to know how to show the application login when a user opens or returns to the application every-time. Most difficult part about this is how to get rid of activities popping out from the stack history.

This is how I did it.

I marked the main activity as



  <activity
            android:name=".ui.MainSettingsActivity" android:label="@string/app_name" android:launchMode="singleTop" android:clearTaskOnLaunch="true" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>



and prompt for password in `onCreate` and `onNewIntent` in the Activity.java worked like a charm

This way, if the user open a new instance or use a existing from from stack history we can popup for the password.

Key part here is "singleTop".

If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to itsonNewIntent() method, rather than creating a new instance of the activity.


Monday, January 21, 2013

MediaPlayer prepare failed. status=0x1 or other issues related to MediaPlayer in Android

If you are working with Android's MediaPlayer you must have seen error popping up like this so randomly and it's quite frustrating .

After digging in I figure out the easy way to diagnose issues related to this.

First thing you should do is hook up setOnErrorListener

because it gives you a correct error codes related to the error.


mediaPlayer.setOnErrorListener(new OnErrorListener() {
    public boolean onError(MediaPlayer mp, int what, int extra) {
        onPlaybackError();
        return true;
    }
});

Eg,


E/MediaPlayer(): error (1, -17)

When it comes to error codes, Android documentation sucks. You have to go to the source code to look after the error codes to find out whats wrong

Error codes are located here 

In this case it was

const PVMFStatus PVMFErrResource = (-17);

Error due to general error in underlying resource

After some more digging i found out the reason for this error.

Android has a total of 8 instances of the player to share among all apps.

 You are likely to get this error if you have ran out. so watch out!!

Tuesday, January 15, 2013

How to check whether a content provider is installed ?

Today, I had to research on the calender to read the events from the native Android calender. Problem is different version of Android uses different content providers. So, how to find if calendar content provider exists ?


private boolean isCalenderExisit(Activity activity) {
boolean isSuccess = false;
ContentProviderClient calendarClient = activity.getContentResolver().acquireContentProviderClient(
getContentURI());
ContentProviderClient eventClient = activity.getContentResolver().acquireContentProviderClient(
getContentURI());
if (eventClient == null || calendarClient == null) {
isSuccess = false;
}
else {
calendarClient.release();
eventClient.release();
isSuccess = true;
}

return isSuccess;
}
public static Uri getContentURI() {
final Uri CONTENT_URI_PRE_8 = Uri.parse("content://calendar/calendars");
final Uri CONTENT_URI = Uri.parse("content://com.android.calendar/calendars");
if(Build.VERSION.SDK_INT <= 7) {
return CONTENT_URI_PRE_8;
} else {
return CONTENT_URI;
}
}

Monday, December 24, 2012

Android BroadcastReceiver is not working after install ? How to fix this ?

Starting from Android 3.1 after you install an application all broadcast receivers are in "STOPPED" state until you click on the icon and start the application. I wanted dig-in to find a solution for this problem. This is what I discovered under the hood.

 com.android.server.pm.Settings.readStoppedLPw() is invoked on BOOT_COMPLETE and it checks for


String tagName = parser.getName();
if (tagName.equals("pkg")) {
    String name = parser.getAttributeValue(null, "name");
    PackageSetting ps = mPackages.get(name);
    if (ps != null) {
        ps.stopped = true;
        if ("1".equals(parser.getAttributeValue(null, "nl"))) {
            ps.notLaunched = true;
        }
    } else {
        Slog.w(PackageManagerService.TAG, "No package known for stopped package: " + name);
    }
so, what is this "nl" ? When you install an apk, your broadcast receiver will listed on /data/system/packages-stopped.xml 


<stopped-packages>
<pkg name="test.broadcast" nl="1" />
</stopped-packages>

So, If you want to enable your packages back, you must modify this file and push it back to /data/system/packages-stopped.xml  with nl="0" 

to get it to work.

and then rebroadcast the BOOT_COMPLETED and you should be fine

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

to do all these you must have root. otherwise no choice

Wednesday, October 3, 2012

How to get all installed SD cards on Android

Today, I wanted to get all installed SD Cards on the device. In Android you can use Environment.getExternalStorageDirectory() get the  external device path but if you have more than 1, (in Galaxy S3 it has 2) you are in trouble. After few hours of Googling i managed to put this code together and hope it will help someone else too..

private static ArrayList<String> mMounts = new ArrayList<String>();
private void dumpAllSDCards() {
mMounts.add("/mnt/sdcard");
     
        try {
            Scanner scanner = new Scanner(new File("/proc/mounts"));
            while (scanner.hasNext()) {
              String line = scanner.nextLine();
              if (line.startsWith("/dev/block/vold/")) {
                String[] lineElements = line.split(" ");
lineElements[1].replaceAll(":.*$", "");
String element = lineElements[1];
                if (!element.equals("/mnt/sdcard")) mMounts.add(element);
              }
            }
          } catch (Exception e) {
           Log.d("MainActivity", e.toString());
          }
     
        for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
File root = new File(mount);
if (!root.exists() || !root.isDirectory() || !root.canWrite())
mMounts.remove(i--);
}
     

        for (String drive : mMounts) {
Log.d("MainActivity", drive + " exist!");
}     
}

Thursday, September 27, 2012

How to create a thumbnail from a video in Android


/**
     * Create a video thumbnail for a video. May return null if the video is
     * corrupt or the format is not supported.
     *
     * @param filePath the path of video file
     * @param kind could be MINI_KIND or MICRO_KIND
     */
    public static Bitmap createVideoThumbnail(String filePath, int kind) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime(-1);
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }

        if (bitmap == null) return null;

        if (kind == Images.Thumbnails.MINI_KIND) {
            // Scale down the bitmap if it's too large.
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int max = Math.max(width, height);
            if (max > 512) {
                float scale = 512f / max;
                int w = Math.round(scale * width);
                int h = Math.round(scale * height);
                bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
            }
        } else if (kind == Images.Thumbnails.MICRO_KIND) {
            bitmap = extractThumbnail(bitmap,
                    TARGET_SIZE_MICRO_THUMBNAIL,
                    TARGET_SIZE_MICRO_THUMBNAIL,
                    OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }

Tuesday, June 19, 2012

How to check whether Android Media Scanner is running ?

Here is the code


    public static final boolean isMediaScannerScanning(final ContentResolver cr) {
        boolean result = false;
        final Cursor cursor = query(cr, MediaStore.getMediaScannerUri(), new String[] { MediaStore.MEDIA_SCANNER_VOLUME }, null,
                null, null);
        if (cursor != null) {
            if (cursor.getCount() == 1) {
                cursor.moveToFirst();
                result = "external".equals(cursor.getString(0));
            }
            cursor.close();
        }
        return result;
    }

How to open a local file in Android browser?

Important thing here is you have to use file:// + path


 private String genLocalPageUrl(String fileName)  {
    return "file://" + this.getFilesDir() + "/" +  fileName ;
 }

How to open browser link in new tab or not open in Android?

This is not something I was not looking for but I just found it. I thought it will be helpful for someone out there.

key point here is putExtra("create_new_tab", false);

Intent  intent  = new Intent("android.intent.action.VIEW", null);
intent.addCategory("android.intent.category.BROWSABLE");
intent.setComponent(paramComponentName);
intent.putExtra("create_new_tab", false); // true or false
intent.putExtra("com.android.browser.application_id", paramComponentName.getPackageName());
startActivity(intent);

Tuesday, May 29, 2012

How to convert and Java project to Android Library project ?

Today, I had to add  reference to a Java project. So I right clicked on the project and checked Properties but there was no "Android" in the treeview in the properties. How to fix this ?

1. Right click and close the project.
2. Open the .project file in notepad.
3. Search for <natures> </natures> tag and change to

<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
4. Save the file and open again in Eclipse.
5. Now you need to create "project.properties" and "AndroidManifest.xml" manually. (I just copied these two files from another project :D)
6. Right click on the project -> Android Tools -> Fix project properties.

After that when I right click and go to properties I can see "Android" in the listview :)



Friday, May 25, 2012

How to change screen timeout to never programmatically?



Settings.System.putString(cr,                     Settings.System.SCREEN_OFF_TIMEOUT, "-1");

Wednesday, May 9, 2012

Your own CountDownTimer in Android


Android CountDownTimer sucks. Why ? because in CountDownTimer.java (Android source code) it creates a mHandler inside the code which requires to call Looper.prepare() and Looper.loop() before calling new CountDownTimer(), You are likely to get Can't create handler inside thread that has not called Looper.prepare() because of this.

  So I wrote my own version of  CountDownTimer using Thread.

Here is it.


abstract class CountDownTimer extends Thread {
    public abstract void onFinish();
    private boolean mCancelled = false;
 
    public void run() {
    mCancelled = false;
    start(60);
    }
 
    private final void start(long secs) {
    long delay = secs * 1000;
do {
delay = delay - 1000;
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
if(mCancelled) {
return;
}
} while (delay > 0);
onFinish();
    }
        public final void cancel() {
    mCancelled = true;
    }
}

How to use
=========


CountDownTimer countDownTimer = new CountDownTimer()  {
@Override
public void onFinish() {

}
};

countDownTimer.start();




Thursday, April 26, 2012

getElementsByTagName returns null in Android 4.0 or 3.0

Today, my application crashed on Android 4 device. I always thought it will work on Android 4 because it was a simple application but I guessed wrong.

For some reason  getElementsByTagName  returns null in Android 4.0 or Android 3.0, if your  code look somewhat like this.


 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 InputSource is = new InputSource(new StringReader("Some XML here and there"));
 Document document = builder.parse(is);
 Element root = document.getDocumentElement();
 root.normalize();
           
 NodeList items = root.getElementsByTagName("tag");  <-- this function will always return null on Android 4 


When i dig in I found a bug reported in Google forums. I found this very hard to believe because this is a very primary level issue and how did it get passed?

Anyway, As a work around I had to use XPath. Just remember to change the project's Android SDK to 2.2 or higher otherwise XPath classes are not visible. They resides in javax.xml.xpath namespace. Or you can use XmlPullParser which reads documents from top to bottom.


InputSource is = new InputSource(new StringReader("Some XML here and there"));
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
NodeList nodeList = (NodeList) xPath.evaluate("/xpath", is, XPathConstants.NODESET);




Sunday, March 11, 2012

Android requires compiler compliance level 5.0. Please fix project properties

Today, I moved a different work space from my old work space, but I imported some of the projects from my previous project and I started to get this error out of no where. I figure out it's something to do with the Eclipse compiler issue. To fix this you need to change globe flag which is located here

Window - > Preferences -> Java -> Compiler - > Change JDK compiler complience level to 1.5 or greater. (I use 1.6)

Tuesday, February 7, 2012

Wi-Fi Keep Alive / On for Kindle Fire

I have uploaded my first app to Amazon App Store, Check it out here

Wi-Fi Keep Alive


It is a simple for kindle fire to keep the wi-fi connection always on even the device screen goes off. This might use some extra battery power to keep the Wi Fi up but it wont disconnect your streaming music :)

Tuesday, January 31, 2012

debug.keystore keystore password ?

Today when i wanted to play with Google Maps, i had to generate a new Certificate fingerprint to include Maps. To generate a new Certificate fingerprint you need to use the keytool that comes with the SDK,

so i executed this line in the CMD,

keytool -list -keystore .android/debug.keystore

but it's asking for a password, duh! after few seacrches on google, I found out, it's android, type android and you shall passed