Wednesday, May 16, 2012

How to unblock the Internet (anonymous browsing)

I am tired of organizations trying to stop their employees from accessing sites like Facebook, MySpace, linkedin and even blogspot and lots of other websites that contain useful work related information. If someone is going to waste time while on job, they will find other ways to do so. Blocking these websites wont change a thing.
If you happen to work in such an organization or if you just want to remain anonymous while browsing online, Tor is what you are looking for. From their home page
"Tor is free software and an open network that helps you defend against a form of network surveillance that threatens personal freedom and privacy, confidential business activities and relationships, and organization state security known as traffic analysis"
Tor accomplishes this by routing your traffic through intermediate nodes(called relays) so someone watching your internet connection wont know which sites you are visiting and the sites you visit wont know your physical location.
Its realy easy to setup Tor on your machine. Below are the steps to use Tor with Chrome on windows machine.
  1. Download Tor from their download page and install it. You will need the Vidalia Bundle
  1. Run Vidalia. This will bring up the Vidalia Control Panel. let it connect to the relay network. When its done minimize it.
  1.  Now open Chrome and install Proxy Switch from Chrome Webstore. This is a proxy manager and it will enable you to switch to using Tor by a single click.
  2. Open options for Proxy Switchy and add a proxy profile. Name it Tor for easy reference and point it to 127.0.0.1:8118

and thats it. Now when you want to switch to anonymous browsing, just click on the Proxy Switchy icon on the address bar and select the Tor profile and you will be anonymous.


Friday, April 6, 2012

My Kindle Fire with Cyanogenmod 7

I just installed Cyanogenmod 7 on my Kindle Fire. It took some time to get things right but it looks awesome now. I was really getting tired of Amazon not allowing me to install even free apps. Waiting for Cyanogenmod 9 AKA Ice Cream Sandwich for Kindle Fire :D




Tuesday, February 21, 2012

C Language: Struct packing and member alignment.

I know this has been discussed and re-discussed at so many locations and so many times that me writing about it again wont make much of a difference but I still see so many people confused about this that I cant stop my self from writing about it.

By default C compilers properly align each member of struct. This means that a 2-byte member e.g. short is aligned on 2-byte boundary, a 4-byte member e.g. int is aligned on 4-byte boundary and so on. This is done so that the struct members can be accessed efficiently and to reduce cache misses. To ensure proper alignment compilers add padding bytes to structs. Consider for example the following struct:
struct SomeData
{
    char Data1;
    short Data2;
    int Data3;
    char Data4;
};

Now as you can can see we are only using 8 bytes for data, but the compiler will add padding bytes to this struct to ensure proper alignment of its member. So a variable of this struct type will actually be like this after compilation on a 32-Bit machine:
struct SomeData
{
    /* 1 byte */
    char Data1; 
    /* 1 byte so the following 'short' can be aligned on a 2 byte boundary*/
    char Padding1[1]; 
    /* 2 bytes */
    short Data2;
    /* 4 bytes - largest struct member */
    int Data3;
    /* 1 byte */
    char Data4;
    /* 3 bytes to make total size of the struct 12 bytes */
    char Padding2[3];
};

The compiled size of the structure is now 12 bytes. It is important to note that the last member is padded with the number of bytes required to make total size of the struct a multiple of the size of the largest member of a struct. In this case 3 bytes are added to the last member to pad the struct to the size of a 12 bytes (4 bytes of int × 3).

As you can see, we are wasting memory. We can off course stop compiler from doing this by asking compiler to pack structs tightly (using #pragma pack() with gcc) but then we lose performance benefits of proper alignment.

In order to avoid these padding bytes but still have proper alignment, we can rearrange this struct so that larger members are listed before the smaller ones. So the above struct can be rearranged as:
struct SomeData
{
    int Data3;
    short Data2;
    char Data1;
    char Data4;
};
Now this does not require any padding as every element is already properly aligned and the overall size of the struct is a multiple of the largest member i.e 4*2 = 8. This is off-course just an example and in reality, even if you arrange your struct members this way, there will still be some padding at the end of the struct to make total size of the struct a multiple of the size of the largest struct member
So please always arrange members of your structs in decreasing order of their size.

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);
 }
}

Thursday, February 9, 2012

Android: How to transform/scale a bitmap and draw it on Canvas without losing quality

If you want to rotate a bitmap and paint it on a Canvas in an Android app, you will probably use Canvas.rotate(degrees) to rotate the canvas and then paint your bitmap using any of Canvas.drawBitmap methods. Nothing fancy but the painted image will be too pixelated - except when the rotation is in multiple of 90 degrees.

The last argument to all Canvas.drawBitmap* methods is a Paint object and most of the examples I found on internet were passing a null for it. To avoid, rather reduce, the pixelation we need to use this Paint object. Create a paint object as mentiond below and pass it as a last argument to your drawBitmap() call.
Paint paint= new Paint(Paint.FILTER_BITMAP_FLAG |
                       Paint.DITHER_FLAG |
                       Paint.ANTI_ALIAS_FLAG);
This will significantly reduce pixelation and your app will look a lot better.

Saturday, December 17, 2011

Android: Debugging your application on real hardware (phone/tablet) on Ubuntu 10.10

If you own an Android smartphone and want to debug your application on your smartphone instead of emulator, you need to declare your application debuggable and setup your device.

To declare your application debuggable, add android:debuggable="true" to  element in your application's AndroidManifest.xml

To setup your device, connect it to your computer with a usb cable and run following command:
adnan@adnan-laptop:~$ adb devices
List of devices attached
emulator-5554 device
???????????? no permissions
if the output contains a line with many question marks (?), as in the above example, then Ubuntu was not able to identify your device. In this case create the file /etc/udev/rules.d/51-android.rules and add following line to it:
SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"
Here the 0bb4 is the vendor id for HTC (Check the list of vendor ids at the end of this post for vendor id of your device) Now unplug and replug the usb cable connecting your device and again  run "adb device":
adnan@adnan-laptop:rules.d$ adb devices
List of devices attached
emulator-5554 device
SH1A6TR23522 device
Your device is ready now and can be used for debugging an application but before trying to install and debug your application on this device, make sure that you have selected the following options on your device:
Settings->Applications->Unknown sources
Settings->Applications->Development->USB debugging
Now when your run your app from Eclipse, you will be presented with a dialog of available emulators and devices. To run your app on device instead of emulator select the device from this dialog and your app will be installed and run on the device.



Vendor IDs:

CompanyUSB Vendor ID
Acer0502
ASUS0B05
Dell413C
Foxconn0489
Garmin-Asus091E
Google18D1
Hisense109B
HTC0BB4
Huawei12D1
K-Touch24E3
KT Tech2116
Kyocera0482
Lenevo17EF
LG1004
Motorola22B8
NEC0409
Nook2080
Nvidia0955
OTGV2257
Pantech10A9
Pegatron1D4D
Philips0471
PMC-Sierra04DA
Qualcomm05C6
SK Telesys1F53
Samsung04E8
Sharp04DD
Sony Ericsson0FCE
Toshiba0930
ZTE19D2

Wednesday, August 31, 2011

Android: How to start MusicPlayer without specifying any music file

Recently I needed to launch standard MusicPlayer from withing my app but without specifying any media file. The requirement was to show the MusicPlayer but not to play anything by default. User can then browse their music file and play any music they want, just as they would do if they launched the music player from home screen.

There are many resources on the web which discuss how to play media using media player. To do this you simply create an intent and add the media files URI to it as data and set the action to Intent.ACTION_VIEW. This will launch the player and play the specified media file. But if you skip adding media file to the intent, Android complains that no app can handle this intent.

So to open the player without media file, I looked at the code of Music Widget in Android source. The intent being used there to launch the player is created as follows
intent = new Intent(context, MusicBrowserActivity.class);
But this doesn't work if I use it as it is because this class, MusicBrowserActivity, can not be resolved. I know that the package for this class is com.android.music but I cant import this package. After trying a lot of things, I was finally able to do this using the following code.
intent = new Intent();
ComponentName comp = new ComponentName("com.android.music", "com.android.music.MusicBrowserActivity");
intent.setComponent(comp);
Hope this helps.