Thursday, March 24, 2011

getSystemService() calls are nearly free

Random fact of the day: calls to Context.getSystemService(servicename) are close to be free of overhead if they are called multiple times in the same program.

I had a look into the source of the ContextImpl class where mostly code like this is used to return services:

private AlarmManager getAlarmManager() {
synchronized (sSync) {
if (sAlarmManager == null) {
IBinder b = ServiceManager.getService(ALARM_SERVICE);
     IAlarmManager service = IAlarmManager.Stub.asInterface(b);
       sAlarmManager = new AlarmManager(service);
    }
  }
    return sAlarmManager;
}



So it's nearly free to request a systemservice multiple times which comes handy when you need to pass multiple managers around in your program. You don't have to pass them into every class, the context is just enough.

This creates a nice interface for the caller as he doesn't need to know and/or create all the objects you need. All he knows is that you need a Context which enables you to freely change your implementation at any given time without changing your interface.

Friday, January 21, 2011

How to write a mail with an attachment on Android

Creating a mail on Android which the user may send with the app of his choice is widely spread on the net. But it isn't how you attach a file which will be send by googlemail.

The problem here is that the gmail app only want to send files which are located on the sdcard


Intent mail = new Intent(android.content.Intent.ACTION_SEND);
mail.setType("application/octet-stream");
mail.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"my@mail.com"});
mail.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
mail.putExtra(android.content.Intent.EXTRA_TEXT, "Message");
mail.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/file.txt"));
PrefAct.startActivity(Intent.createChooser(mail, "Send mail via..."));


As said gmail will refuse your attachment when the user sends the mail when the file isn't located on the ExternalStorage.