Tuesday, November 30, 2010

android.view.WindowManager$BadTokenException & Android – Displaying Dialogs From Background Threads

Having threads to do some heavy lifting and long processing in the background is pretty standard stuff. Very often you would want to notify or prompt the user after the background task has finished by displaying a Dialog.

The displaying of the Dialog has to happen on the UI thread, so you would do that either in the Handler object for the thread or in the onPostExecute method of an AsyncTask (which is a thread as well, just an easier way of implementing it). That is a textbook way of doing this and you would think that pretty much nothing wrong could go with this.

Surprisingly I found out that something CAN actually go wrong with this. After Google updated the Android Market and started giving crash reports to the developers I received the following exception:

android.view.WindowManager$BadTokenException: Unable to add window — token android.os.BinderProxy@447a6748 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:468)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:239)
at android.app.Activity.showDialog(Activity.java:2488)

at android.os.Handler.dispatchMessage(Handler.java:99)

I only got a couple of these exceptions from thousands of installs, so I knew that was not anything that happens regularly or that it was easy to replicate.

Looking at the stack trace above it gives us a pretty good idea why it failed. It started in the Handler object, which naturally was called by a background thread after it finished its processing. The Handler instance tried to show a Dialog and before it could show it, it tried to set the View for it and then it failed with:

android.view.WindowManager$BadTokenException: Unable to add window — token android.os.BinderProxy@447a6748 is not valid; is your activity running?

The 447a6748 number is just a memory address of an object that no longer exists.

Note- do not get hung up on the exact number. It would be different with every execution.

Now we know why the application crashed, the only thing left is to figure out what caused it?

We know that background threads execute independently of the main UI thread. That means that the user could be interacting with the application during the time that the thread is doing its work under the covers. Well, what happens if the user hits the “Back” button on the device while the background thread is running and what happens to the Dialog that this thread is supposed to show? Well, if the timing is right the application will most likely crash with the above described error.

In other words what happens is that the Activity will be going through its destruction when the background thread finishes its work and tries to show a Dialog.

In this case it is almost certain that this should have been handled by the Virtual Machine. It should have recognized the fact that the Activity is in the process of finishing and not even attempted to show the Dialog. This is an oversight of the Google developers and it will probably be fixed some time in the future, but in the meantime the burden is on us to take care of this.

The fix to this is pretty simple. Just test if the Activity is going through its finishing phase before displaying the Dialog:

private Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
if (!isFinishing()) {

Wednesday, November 10, 2010

Host File - Windows

The hosts file is a computer file used in an operating system to map hostnames to IP addresses. The hosts file is a plain-text file and is traditionally named hosts.

The hosts file is one of several system facilities to assist in addressing network nodes in a computer network. It is a common part in a operating system's Internet Protocol (IP) implementation, and serves the function of translating human-friendly hostnames into numeric protocol addresses, called IP addresses, that identify and locate a host in an IP network.
In some operating systems, the host file content is used preferentially over other methods, such as the Domain Name System (DNS), but many systems implement name service switches (.e.g., nsswitch.conf) to provide customization. Unlike the DNS, the hosts file is under the direct control of the local computer's administrator.

#This is an example of the hosts file localhost loopback
::1 localhost

path of host file is:

Windows 95/98/Me c:\windows\hosts

Windows NT/2000/XP Pro c:\winnt\system32\drivers\etc\hosts

Windows XP Home c:\windows\system32\drivers\etc\hosts

Monday, November 8, 2010

List of Running ApplciationS

From the below snippet we can check the list of running applications and check whether your application is in foreground or not.

ActivityManager actvityManager = (ActivityManager)
this.getSystemService( ACTIVITY_SERVICE );
List procInfos = actvityManager.getRunningAppProcesses();

boolean appFound = false;

for(int i = 0; i < procInfos.size(); i++)
if(procInfos.get(i).processName == "com.android.camera")
appFound = true;

if (appFound)
Toast.makeText(getApplicationContext(), "Camera App is running!!!!", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Camera App is not running!!!!", Toast.LENGTH_LONG).show();

the above snippet shows your camera application is running or not.

Sunday, November 7, 2010

UI/Application Exerciser Monkey

Today i gone through this tutorial from developer site seems to be interesting for UI application performance ,adding basic information on my blog:

---Basically Monkey is a program that runs on you emulator or Device(Mobile) and generates pseudo-random streams of user events such as clicks, touches, or gestures, as well as a number of system-level events.

---You can use the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.

Description of Monkey Tool:

--The Monkey is a command-line tool that that you can run on any emulator instance or on a device. It sends a pseudo-random stream of user events into the system, which acts as a stress test on the application software you are developing.


The Monkey includes a number of options, but they break down into four primary categories:
1.Basic configuration options, such as setting the number of events to attempt.
2.Operational constraints, such as restricting the test to a single package.
3.Event types and frequencies.
4.Debugging options.

****When the Monkey runs, it generates events and sends them to the system. It also watches the system under test and looks for three conditions, which it treats specially:

1.If you have constrained the Monkey to run in one or more specific packages, it watches for attempts to navigate to any other packages, and blocks them.
2.If your application crashes or receives any sort of unhandled exception, the Monkey will stop and report the error.
3.If your application generates an application not responding error, the Monkey will stop and report the error.

Depending on the verbosity level you have selected, you will also see reports on the progress of the Monkey and the events being generated.

Basic Use Steps for Monkey:

****You can launch the Monkey using a command line on your development machine or from a script. Because the Monkey runs in the emulator/device environment, you must launch it from a shell in that environment. You can do this by prefacing adb shell to each command, or by entering the shell and entering Monkey commands directly.

The basic syntax is:

$ adb shell monkey [options]

With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will send events to any (and all) packages installed on your target. Here is a more typical command line, which will launch your application and send 500 pseudo-random events to it:

$ adb shell monkey -p your.package.name -v 500

Command Options Reference

The below lists all options you can include on the Monkey command line.

1. --help : Prints a simple usage guide.

2. -v : Each -v on the command line will increment the verbosity level. Level 0 (the default) provides little information beyond startup notification, test completion, and final results. Level 1 provides more details about the test as it runs, such as individual events being sent to your activities. Level 2 provides more detailed setup information such as activities selected or not selected for testing.

3. -s : Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed value, it will generate the same sequence of events.

4. --throttle : Inserts a fixed delay between events. You can use this option to slow down the Monkey. If not specified, there is no delay and the events are generated as rapidly as possible.

5. --wait-dbg : Stops the Monkey from executing until a debugger is attached to it.

etc., command for debugging, constraints, events & general commands refer android developer site for more information.

Friday, November 5, 2010

Developing a Device Administration Application

System administrators can use the Device Administration API to write an application that enforces remote/local device security policy enforcement. This section summarizes the steps involved in creating a device administration application.

Creating the manifest:
To use the Device Administration API, the application's manifest must include the following:

A subclass of DeviceAdminReceiver that includes the following:
--The BIND_DEVICE_ADMIN permission.
--The ability to respond to the ACTION_DEVICE_ADMIN_ENABLED intent, expressed in the manifest as an intent filter.

A declaration of security policies used in metadata.

Here is an snippet for the Device Administration sample manifest:


android:resource="@xml/device_admin_sample" />

Note that:

The activity in the sample application is an Activity subclass called Controller. The syntax ".app.DeviceAdminSample$Controller" indicates that Controller is an inner class that is nested inside the DeviceAdminSample class. Note that an Activity does not need to be an inner class; it just is in this example.

The following attributes refer to string resources that for the sample application reside in ApiDemos/res/values/strings.xml. For more information about resources, see Application Resources.

android:label="@string/activity_sample_device_admin" refers to the user-readable label for the activity.

android:label="@string/sample_device_admin" refers to the user-readable label for the permission.

android:description="@string/sample_device_admin_description" refers to the user-readable description of the permission. A descripton is typically longer and more informative than a label.

android:permission="android.permission.BIND_DEVICE_ADMIN" is a permission that a DeviceAdminReceiver subclass must have, to ensure that only the system can interact with the receiver (no application can be granted this permission). This prevents other applications from abusing your device admin app.

android.app.action.DEVICE_ADMIN_ENABLED is the the primary action that a DeviceAdminReceiver subclass must handle to be allowed to manage a device. This is set to the receiver when the user enables the device admin app. Your code typically handles this in onEnabled(). To be supported, the receiver must also require the BIND_DEVICE_ADMIN permission so that other applications cannot abuse it.

When a user enables the device admin application, that gives the receiver permission to perform actions in response to the broadcast of particular system events. When suitable event arises, the application can impose a policy. For example, if the user attempts to set a new password that doesn't meet the policy requirements, the application can prompt the user to pick a different password that does meet the requirements.

android:resource="@xml/device_admin_sample" declares the security policies used in metadata. The metadata provides additional information specific to the device administrator, as parsed by the DeviceAdminInfo class. Here are the contents of device_admin_sample.xml:

Implementing the code

The Device Administration API includes the following classes:


Base class for implementing a device administration component. This class provides a convenience for interpreting the raw intent actions that are sent by the system. Your Device Administration application must include a DeviceAdminReceiver subclass.

A class for managing policies enforced on a device. Most clients of this class must have published a DeviceAdminReceiver that the user has currently enabled. The DevicePolicyManager manages policies for one or more DeviceAdminReceiver instances

This class is used to specify metadata for a device administrator component.
These classes provide the foundation for a fully functional device administration application. The rest of this section describes how you use the DeviceAdminReceiver and DevicePolicyManager APIs to write a device admin application.

Subclassing DeviceAdminReceiver

To create a device admin application, you must subclass DeviceAdminReceiver. The DeviceAdminReceiver class consists of a series of callbacks that are triggered when particular events occur.

In its DeviceAdminReceiver subclass, the sample application simply displays a Toast notification in response to particular events. For example:

public class DeviceAdminSample extends DeviceAdminReceiver {

public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");

public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";

public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");

public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");

void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

Enabling the application

One of the major events a device admin application has to handle is the user enabling the application. The user must explicitly enable the application for the policies to be enforced. If the user chooses not to enable the application it will still be present on the device, but its policies will not be enforced, and the user will not get any of the application's benefits.

The process of enabling the application begins when the user performs an action that triggers the ACTION_ADD_DEVICE_ADMIN intent. In the sample application, this happens when the user clicks the Enable Admin button

for Reference's Android Device Administration code

Device Administration - New Feature Supported from Froyo

Android 2.2(FROYO) introduces support for enterprise applications by offering the Android Device Administration API.

--Device Administration API provides device administration features at the system level.

--These APIs allow you to create security-aware applications that are useful in enterprise settings, in which IT professionals require rich control over employee devices.

***For example, the built-in Android Email application has leveraged the new APIs to improve Exchange support. Through the Email application, Exchange administrators can enforce password policies — including alphanumeric passwords or numeric PINs — across devices.

**Administrators can also remotely wipe (that is, restore factory defaults on) lost or stolen handsets.

**Exchange users can sync their email and calendar data.

--This above information is intended for developers who want to develop enterprise solutions for Android-powered devices. It discusses the various features provided by the Device Administration API to provide stronger security for employee devices that are powered by Android.

Device Administration API Overview :

Here are examples of the types of applications that might use the Device Administration API:

--Email clients.
--Security applications that do remote wipe.
--Device management services and applications.

How does it work?

You use the Device Administration API to write device admin applications that users install on their devices. The device admin application enforces the desired policies. Here's how it works:

A system administrator writes a device admin application that enforces remote/local device security policies. These policies could be hard-coded into the app, or the application could dynamically fetch policies from a third-party server.
The application is installed on users' devices. Android does not currently have an automated provisioning solution. Some of the ways a sysadmin might distribute the application to users are as follows:

Android Market.

Enabling non-market installation.

Distributing the application through other means, such as email or websites.

The system prompts the user to enable the device admin application. How and when this happens depends on how the application is implemented.
Once users enable the device admin application, they are subject to its policies. Complying with those policies typically confers benefits, such as access to sensitive systems and data.

If users do not enable the device admin app, it remains on the device, but in an inactive state. Users will not be subject to its policies, and they will conversely not get any of the application's benefits—for example, they may not be able to sync data.

If a user fails to comply with the policies (for example, if a user sets a password that violates the guidelines), it is up to the application to decide how to handle this. However, typically this will result in the user not being able to sync data.

If a device attempts to connect to a server that requires policies not supported in the Device Administration API, the connection will not be allowed. The Device Administration API does not currently allow partial provisioning. In other words, if a device (for example, a legacy device) does not support all of the stated policies, there is no way to allow the device to connect.

If a device contains multiple enabled admin applications, the strictest policy is enforced. There is no way to target a particular admin application.

To uninstall an existing device admin application, users need to first unregister the application as an administrator.

In an enterprise setting, it's often the case that employee devices must adhere to a strict set of policies that govern the use of the device. The Device Administration API supports the policies listed in Table 1. Note that the Device Administration API currently only supports passwords for screen lock:

Table 1. Policies supported by the Device Administration API.
Below explanation with Policy:Description
Password enabled Requires that devices ask for PIN or passwords.

Minimum password length : Set the required number of characters for the password. For example, you can require PIN or passwords to have at least six characters.

Alphanumeric password required : Requires that passwords have a combination of letters and numbers. They may include symbolic characters.

Maximum failed password attempts : Specifies how many times a user can enter the wrong password before the device wipes its data. The Device Administration API also allows administrators to remotely reset the device to factory defaults. This secures data in case the device is lost or stolen.

Maximum inactivity time lock : Sets the length of time since the user last touched the screen or pressed a button before the device locks the screen. When this happens, users need to enter their PIN or passwords again before they can use their devices and access data. The value can be between 1 and 60 minutes.

Other features

In addition to supporting the policies listed in the above table, the Device Administration API lets you do the following:

Prompt user to set a new password.
Lock device immediately.
Wipe the device's data (that is, restore the device to its factory defaults).

Code Snippet to Convert String to Hex-Decimal

A Small Code Snippet to Convert String to Hex-Decimal

class StringtoHexConvertion {

public static void main(String args[]){

String imputString = "000000000002";
byte[] bytes = imputString .getBytes("US-ASCII");

String str1 = "";
for(int i=0;i
System.out.println("byte value = "+ bytes[i]);
str1 = str1 + Integer.toHexString(bytes[i]);
System.out.println(" final String = "+ str1);
catch(Exception e){}

It might be helpful for some sceneries.

SD Card Boot Sequence on Android Platform

When you are porting Android, one important feature to check is SD card mount.

Needless to say this feature is needed for many functions to operate in correctly.

Couple of such examples are Bluetooth OPP and FTP profiles.

SD card boot up sequence is as follows :

mmc/sd driver recognises the inserted card, makes device object for every partitions

with unique combination of MAJOR:MINOR numbers and generate uevent.

uevent comes to user-level via kernel socket NETLINK_KOBJECT_UEVENT.

vold handles this uevent in uevent.c::handle_block_event().

vold reads boot sector to determine, how many partitions remains on storage.

If all partitions are found, vold will start "mount" procedure.

If mount is successfully finished, vold sends "volume_mounted:/sdcard" to


com.android.server.MountListener dispatches message to

com.android.server.MountService by handleEvent() method.

com.android.server.MountService provides to framework the logical interpretation of

vold actions such as update icon notification and forwards command from user to vold.

So, in our case MountService::notifyMediaMounted() will generate


This intent will start com.android.providers.media.MediaScanner which will start

searching the media content and makes the database. Parallely

com.android.settings.deviceinfo.Memory will update memory status.

Some important files to remember for SD card boot sequence are mmc.c,

ums.c vold.c, voldmgr.c, uevent.c. These files will be useful in debugging SD card

boot up sequence. The configuration file of SD card is vold.conf and is present in


Trick to show Your Name after time in Taskbar

I am interested to share a funny trick with time display in the taskbar....Let us see.....

Trick to show ur Name after time in taskbar....

Here is a trick to add up ur name in place of AM and PM beside time and make urself to feel proud among ur group of friends...
Its simple....

Start -> Control Panel -> Regional and Language option -> Customize (beside English US) -> Go to TIME tab -> change AM or PM symbols from AM or PM to ur name or the word u like to display-> Apply -> OK

How to Hide the drives?

How to Hide the drives(c:,d:,e:,a:...etc)
How to Hide the drives(c:,d:,e:,a:...etc)
This is a great trick you can play on your friends. To disable the display of local or networked drives when you click My Computer.

1.Go to start->run.Type regedit.Now go to:


Now in the right pane create a new DWORD item and name it NoDrives(it is case sensitive). Now modify it's value and set it to 3FFFFFF (Hexadecimal) .Now restart your computer. So, now when you click on My Computer, no drives will be shown(all gone...). To enable display of drives in My Computer, simply delete this DWORD item that you created.Again restart your computer.You can now see all the drives again. Magic.......

Different Ways to Shutdown your Personal Computer

There are so many different ways to turn off your Windows XP computer, let's look at some of them:

1. The standard approach - click the Start Button with your mouse, then select the Turn Off menu and finally click the Turn Off icon on the Turn Off computer dialog. blink.gif

2. Press Ctrl+Esc key or the Win key and press u two times - the fastest approach.

3. Get the Shutdown utility from Download.com - it add the shut down shortcuts for you. Else create them yourself using approach 4.

4. Create a shutdown shortcut on your desktop. Right click on the desktop, choose New Shortcut and type shutdown -s -t 00 in the area where you are asked to specify the location of the program file. Now you can just double click this icon to turn off the computer. The best location would be your quick launch bar.

5. Press the Win key + R key to open the run window. Type shutdown -s -t 00. [s means shutdown while t means the duration after which you want to initiate the shutdown process].

If some open processes or application won't let you turn off, append a -f switch to force a shut down by closing all active processes.

6. Win+M to minimize all windows and then Alt+F4 to bring the Turn Off computer dialog.

7. Open Windows Task manager (by right clicking the Windows Task bar or Alt+Ctrl+Del) and choose Shut down from the menu. Useful when the Windows are not responding.

World Trade Center Trick from NotePad:

Trick to find the World Trace Center crash Logic.

1.Open NotePad, type World Trade Center crash flight number Q33N.

2. Increase your font size to 72.

3. change the font type to Wingdings.

and check the result.

How was the result?????