Posts

Showing posts from July, 2014

Android - When scale animations wouldn't change height and width

Image
   One might assume that Android's animation especially the ones based on property animation APIs (since 11) would actually change the view properties. A scale animation gives a feel that a view's height and width is actually changed. However, the view APIs like getWidth() and getHeight() would still return the old unchanged values. So how exactly is the view shown after scale and how does it respond to touch events? Would the scaled section of the view accept input events? Well, it depends on the layout. A simple layout with just one view might seem to work but the problem can be seen with a layout having multiple views.     In this case, a linear layout has two image views in vertical orientation. Clicking the first image causes it to scale out. View.setScaleX and View.setScaleY doesn't actually change the width and height of the view and hence it doesn't alter the location of the second image view in the layout. Due to this, clicks on the section of the second ...

Android - Rotate animation with Zoom effects

    Android's object animation is quite powerful to control different view attributes. The only catch is that complex animations needs code changes and just can't be done via xml alone. In this case, the animation is to rotate an image along Y axis along with a zoom effects. The zoom works half way through the animation and goes the other way.     Its possible to achieve this via both rotation and scale animation. However, this illustration is just to demonstrate the different possible customizations via property animation. The idea is to just listen for Animation Updates provided by ValueAnimator (base of ObjectAnimator) and use this update's AnimatedFraction to calculate desired values during the animation, padding in this case. The animated fraction varies from 0 to 1 for all kinds of animation. A value of 0.5 indicates that the animation is half done.         final int animationPadding = 100;         Object...

Android - Dialog on top of foreground activity

      One of the annoying prerequisites of a Dialog is its dependency of a valid context. This can be a pain for an application having multiple activities with a lot of book keeping etc. Wish the framework exposed an API to display the dialog with its available info. Unfortunately, until then this extended version of the Application works good enough. Internally, it keeps track of the resumed activity and exposes a API showDialog(). public class DialogApplication extends Application {     private WeakReference<Context> mActiveContext;     private ActivityLifecycleCallbacks mRegisteredListeners;     public DialogApplication() {         super.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {             @Override             public void onActivityCreated(Activity activity, Bundle bundle) {           ...

Android Binder IPC - File Transfer

      Android's Binder IPC like many other alternatives supports file transfer. However this is a most efficient implementation of constant order, irrespective of the file size. This makes is very suitable to transfer pictures, videos etc of many mega bytes in size from one application to the other. So how does this work and how is this different from traditional linux approach?     Well, there isn't any file manipulation like opening the file, reading and streaming its contents. Instead, its just a smart manipulation of the file descriptors in the source and destination process space. Most of binder logic is loaded as a kernel module and it gets to run with enough permissions to  manipulate process file descriptor table. Its implemented by a special binder transaction BINDER_TYPE_FD. Upon request, binder determines if the target of the transaction can accept files and if so, gets a reference to the destination process's file descriptor table and an...

Android's HandlerCaller - Decorator pattern

     Android's code base is a rich source for object oriented patterns. One such is the decorator pattern used in HandlerCaller. The Handler implementation had the support to send a message with a maximum of two integers and one Object type. But what if a component wanted to send more than one Object? Well, they could just nest all these types into a master type and handle the logic by themselves. And this additional functionality is what is decorated in HandlerCaller. Internally, it just uses SomeArgs to nest multiple objects and uses the standard Handler APIs. The only catch is that this is an internal API and can't be used via SDK.     public Message obtainMessageIIOO(int what, int arg1, int arg2,             Object arg3, Object arg4) {         SomeArgs args = SomeArgs.obtain();         args.arg1 = arg3;         args.arg2 = arg4;         retu...

Android's Watchdog daemon

    Android framework's Watchdog (Java implementation) is meant to handle cases when the framework ends up in an unresponsive state. However, this doesn't help handle kernel or other OEM specific driver issues. Chip vendors usually provide a hardware watchdog to hard reset the system to handle software failures. The hardware watchdog just waits to be reset by software within a specific duration and force resets the system if otherwise. The hardware watchdog is just handled by a vendor specific watchdog driver and it exposes IOCTL APIs for user space to set timeout interval, reset the watchdog etc. So does Android provide any support?     Its supported by a daemon process (/sbin/watchdogd) and OEMs could use this to fine tune timeout intervals or even completely disable it. watchdogd is really a symbolic link to init process.     lrwxrwxrwx root     root              1969-12-31 19:00 watchdogd -> ../init ...

Android Studio - Javadoc task

Image
  Gradle task to generate Javadoc     The task definition shouldn't be within the Android block and in this case, its used in an application project. For a library project, just replace android.applicationVariants to android.libraryVariants. The task refers to the source code and the Android's SDK jar and excludes build generated source files. android {     compileSdkVersion 19     buildToolsVersion '19.1.0'     defaultConfig {         minSdkVersion 19         targetSdkVersion 19         versionCode 1         versionName "1.0"     }     buildTypes {         release {             runProguard false             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'         }     } } andro...

Android - Access Application's private data

      Ever wanted to check whats being stored by your favorite application? Well, one option is to root the device and get unlimited adb access to the app's private data        adb pull /data/data/com.example.android.softkeyboard  The package name can be found in /data/system/packages.xml     What if the device isn't rooted? Well, there are two options provided debugger support is enabled in the device. The app should either be debuggable or should support backup (android:allowBackup). An app is debuggable if the third column in /data/system/packages.list is 1 and if it is use the following commands to run the shell commands as the app. com.android.development_settings 10022 0 /data/data/com.android.development_settings release none com.example.android.softkeyboard 10057 1 /data/data/com.example.android.softkeyboard default 1028,1015       adb shell      $ run-as com.example.android.softkeyboa...

Android - Dialog via Service context

Image
    Android's UI Toolkit requires a valid context to be created. A valid context isn't necessarily an alive context instead one which has a valid window token associated with it. So an attempt to create and add a view in a service context, application context, broadcast receiver context will fail with a android.view.WindowManager$BadTokenException much like adding a view via context of a destroyed activity (although this would be a typical bug of holding active references to context even after the user is finished with it, like a internal non-static Handler implementation in an Activity).      However, the InputMethod views are always shown via InputMethodService which is a more specific implementation of a Service. For a developer, InputMethodService offers getLayoutInflater() and helper callbacks like onCreateInputView(), onCreateCandidatesView() etc to display the soft keyboard. So how does this work only for this type of service? what context is exactly b...

Android - application loses sate upon resume

    Android's application typically remember the state when pushed into background and this state is used when the user resumes the application. This state is saved in framework process space instead of the application process as this is also meant to handle cases when the process gets killed by low memory killer to help Android recover memory for other foreground application's need. When user resumes this application via Launcher or Recent apps, a new process is created and the previous state is passed on to the activities hosted in the new process. The entire operation is transparent to the user and offers a seamless experience. The only prerequisite is that the applications should be coded well to save and restore instance state.    This sounds good, however, i recently noticed few apps losing state despite saving their state. I was sure of the application as i had coded this one and the logic worked fine for most of the time and it fails only in few cases...

Android - Application onDestroy or finalize

Image
       Why doesn't android's Application class have a onDestroy callback? How is one supposed to clean up resources allocated in Application's onCreate? Should Java's finalize() API instead be used?         The reason why Application doesn't have a onDestroy is because its never supposed to be destroyed. The application instance is created once to host the first component of the application (activity, service, broadcast receiver or content provider) and once created, its lifetime is tied to that of the process. It stays alive even when the user is finished using application components (empty process). From here on, it is used to host new components of the same applications, should one be launched. The only case where is cleaned up from memory is when the process is terminated either due to low memory killer or explicit user requests etc.    So what prevents the dalvik's garbage collector to clean it up the instance in an empty proce...

Android - Timeout for Login based applications

Image
   Quite a few android applications have to authenticate users and as a security measure have to implement a timeout logic to ensure that the user is signed out of the application. I have seen implementations where in a thread is started and it periodically posts a message to main thread's handler and thats one way to sign out the user. The downside is the extra thread, context switch, additional application logic etc.    Android's Activity Manager had a hidden feature which can be used for applications implementing a 30 minute timeout. The original idea behind this feature is that when user performs a task like sending an email with a picture attachment, its possible that the user might have to do something else while in the gallery activity (to attach the picture), the entire task could be pushed to background and user might return to this task later on. In this case, the odds of the user remembering as to why the gallery activity was open is less, should he re...