Thursday, February 16, 2012

Android: How to start vendor specific Alarm Clock on any Android device?

Alarm clock is a nice to have feature for many applications and because of Intents you dont need to code this functionality in every app where you want it. For Android, adding an Alarm Clock to your application is as simple as launching an Intent for the built-in Alarm Clock of the device. The only issue here is that different manufacturers i.e HTC, Google, Samsung, Sony Ericson have their own implementation of Alarm Clock and there is no single intent that will automatically launch which ever Alarm Clock is present on the device. So to start Alarm Clock, you will first need to check which Alarm Clock is present on the device that the app is running on and then launch that Alarm clock.

The code below is what I used in one of my recent apps:
private void startAlarmActivity()
{
 PackageManager packageManager = getPackageManager();
 Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN)
                                     .addCategory(Intent.CATEGORY_LAUNCHER);

 // Verify clock implementation
 String clockImpls[][] = {
    { "HTC", "com.htc.android.worldclock",
    "com.htc.android.worldclock.WorldClockTabControl" },
    { "Standard", "com.android.deskclock", 
    "com.android.deskclock.AlarmClock" },
    { "Froyo", "com.google.android.deskclock", 
    "com.android.deskclock.DeskClock" },
    { "Motorola", "com.motorola.blur.alarmclock",
    "com.motorola.blur.alarmclock.AlarmClock" },
    { "Sony Ericsson", "com.sonyericsson.alarm", "com.sonyericsson.alarm.Alarm" },
    { "Samsung", "com.sec.android.app.clockpackage", 
    "com.sec.android.app.clockpackage.ClockPackage" } };

 boolean foundClockImpl = false;

 for (int i = 0; i < clockImpls.length; i++)
 {
  String packageName = clockImpls[i][1];
  String className = clockImpls[i][2];
  try
  {
   ComponentName cn = new ComponentName(packageName, className);
   packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
   alarmClockIntent.setComponent(cn);
   foundClockImpl = true;
   break;
  }
  catch (NameNotFoundException e)
  {
   Log.d("ADNAN", "Alarm clock "+clockImpls[i][0]+" not found");
  }
 }
 if (foundClockImpl)
 {
  alarmClockIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(alarmClockIntent);
 }
}

No comments: