martes, 15 de febrero de 2011

Android: write EASY on internal storage

Recently I found that not all sdcards filesystem root paths starts with /sdcard. So I was getting an Exception trying to write files in a location that doesn't exist. Epic fail in my code.

Filesystem root path independent code

String content = "Hola mundo";       
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);

This will create a file on your application private space, so no other applications can access to it.

Great thing is that you don't need to know anything about paths, permissions, inputstreams, ... Just let Android handle it for you.

viernes, 11 de febrero de 2011

Android: my custom log class

I use a custom log class on all my Android projects to easy my life.

  • Possibility to enable/disable log by configuration. Useful to keep your releases clean.
  • Class call trace. Know which class is displaying which log message with no extra text.

How it's done?

Really easy. Just create a new class:
class Log {
public final static String LOGTAG = "Phone2Chrome";
static final boolean LOGV = true;

static void v(String logMe) {
 if (LOGV) {
  try {
   throw new Exception("go go logger");
  } catch (Exception e) {
   String className = e.getStackTrace()[1].getClassName();
   className = className.substring(className.lastIndexOf(".")+1, className.length());
   android.util.Log.v(LOGTAG, className + "." + e.getStackTrace()[1].getMethodName() + "() --- " + logMe);

Import it in your Android classes and make this replacement:
void myFunction() {
- Log.d(TAG, "MyActivity - myFunction: hello logcat");
+ Log.v("hello logcat");

What you are going to see in logcat is something like this:

V/Phone2Chrome(16119): MyActivity.myFuntion() --- hello logcat.

No more dirty log messages anymore!

domingo, 6 de febrero de 2011

New chrome tab with dynamic content injection

To create a new chrome tab and inject content dynamically on it you need to use:
  • chrome.tabs.create: on main script 
  • chrome.tabs.sendRequest: on main script
  • chrome.extension.onRequest: on new tab
Take a look at the API doc for more info: 

Main script
chrome.tabs.create({url: "NewTabView.html"}, 
 function (tab) {
  // Callback function is called when tab is created.
  chrome.tabs.sendRequest(, {content: "hello tab"}