Saturday, May 3, 2014

Android: adding backstack to the Pushnotification Activity

When User has an action on notifications, the activity is launching on tap of the notification but on press back application closes normally.

We can open activity rather than closing application on back press.

How to achieve this?

By building back stack to the application, when coming from the notification.
So, we need to know about the parentActivityName and Create back stack when starting the activity

Specify parent activities in the manifest

Beginning in Android 4.1 (API level 16), we can declare the logical parent of each activity by specifying the android:parentActivityName attribute in the <activity> element.  

<activity android:name="com.vardhan.pushnotificationtest.HomeActivity" />
<activity android:name="com.vardhan.pushnotificationtest.PushNotificationActvity"
          android:parentActivityName="com.vardhan.pushnotificationtest.HomeActivity"  >
</activity>


If your app supports Android 4.0 and lower, include the Support Library with your app and add a element inside the <activity>. Then specify the parent activity as the value for

<activity android:name="com.vardhan.pushnotificationtest.HomeActivity" />
<activity android:name="com.vardhan.pushnotificationtest.PushNotificationActvity" >
         
          <meta-data
                   android:name="android.support.PARENT_ACTIVITY"
             android:value="com.vardhan.pushnotificationtest.HomeActivity" />
</activity>

Create back stack when starting the activity

Adding activities to the back stack begins upon the event that takes the user into your app. That is, instead of calling startActivity(), use the TaskStackBuilder APIs to define each activity that should be placed into a new back stack. Then begin the target activity by calling startActivities(), or create the appropriate PendingIntent by calling getPendingIntent().

// Intent for the activity to open when user selects the notification
Intent displayIntent = new Intent(this, PushNotificationActvity.class);

// Use TaskStackBuilder to build the back stack and get the PendingIntent
PendingIntent contentIntent = TaskStackBuilder.create(this)
                   // add all of SecondActvity's parents to the stack,
                   // followed by SecondActvity itself
                   .addNextIntentWithParentStack(displayIntent)
                   .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

// Creates notification Builder, set small icon, title, style and content to the builder.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                   this).setSmallIcon(R.drawable.ic_stat_gcm)
                   .setContentTitle("GCM Notification")
                   .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                   .setContentText(msg);

// Puts the PendingIntent into the notification builder
mBuilder.setContentIntent(contentIntent);

// Notifications are issued by sending them to the
// NotificationManager system service.
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// Builds an anonymous Notification object from the builder, and
// passes it to the NotificationManager
mNotificationManager.notify(id, mBuilder.build());

The resulting PendingIntent specifies not only the activity to start (as defined by displayIntent), but also the back stack that should be inserted into the task (all parents of the PushNotificationActvity defined by displayIntent). So when the PushNotificationActvity starts, pressing Back navigates backward through each of the PushNotificationActvity class's parent activities.

Note: In order for the addNextIntentWithParentStack() method to work, you must declare the logical parent of each activity in your manifest file, using the android:parentActivityName attribute (and corresponding <meta-data> element) as described above.

Why PendingIntent?
Intent English meaning is intended; pending said the impending advent of things. 
The PendingIntent specifies an action to take in the future. 

By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself (with the same permissions and identity). As such, you should be careful about how you build the PendingIntent

Why to use addNextIntentWithParentStack?
Add a new Intent with the resolved chain of parents for the target activity to the task stack.
This is equivalent to calling addParentStack with the resolved ComponentName of nextIntent (if it can be resolved), followed by addNextIntent with nextIntent.



Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments.

Monday, April 7, 2014

Android: ListView inside a ScrollView

We shouldn’t use ListView inside the ScrollView because the list view is already ScrollView, the items in list view are already scrollable..

Problem / Issue

When we try to add the ListView into the ScrollView, we may face a problem that the list view will show only one item from the adapter.

To solve this issue, we should know the definition of ScrollView.

As per the Android Documentaion:

A ScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects. A child that is often used is a LinearLayout in a vertical orientation, presenting a vertical array of top-level items that the user can scroll through.
You should never use a ScrollView with a ListView, because ListView takes care of its own vertical scrolling. Most importantly, doing this defeats all of the important optimizations in ListView for dealing with large lists, since it effectively forces the ListView to display its entire list of items to fill up the infinite container supplied by ScrollView.

Solution

Calculate the size of the list items and set the height of the ListView programmatically.
Call setListViewHeightBasedOnChildren(listview)  method right after the listView.setAdapter.

public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter(); 
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(00);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
  


Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments.

Monday, March 31, 2014

Android Dependency injection: RoboGuice vs ButterKnife

Dependency injection

Dependency injection is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle. The term was coined by Martin Fowler

Why Dependency injection?

  • Reduction of boilerplate code
  •  It promotes reusability, testability and maintainability.

There is any DI for Android?

Yes, there are many libraries, which support injection in android.
Listed below are used the most in this space.

RoboGuice

RoboGuice is a framework that brings the simplicity and ease of Dependency Injection to Android, using Google's own Guice library.   If you've ever used Spring (the #1 enterprise framework on Java, now more popular than J2EE itself) or Guice, you already know how convenient this style of programming can be.

Android Annotations

AndroidAnnotations is an Open Source framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what's really important. By simplifying your code, it facilitates its maintenance.
  • Dependency injection: inject views, extras, system services, resources, ...
  • Simplified threading model: annotate your methods so that they execute on the UI thread or on a background thread.
  • Event binding: annotate methods to handle events on views, no more ugly anonymous listener classes!
  • REST client: create a client interface, AndroidAnnotations generates the implementation.
  • No magic: As AndroidAnnotations generate subclasses at compile time, you can check the code to see how it works.
  • AndroidAnnotations provide those good things and even more for less than 50kb, without any runtime perf impact!

Dragger

Fast dependency injector for Android and Java.
Dagger is a replacement for these FactoryFactory classes. It allows you to focus on the interesting classes. Declare dependencies, specify how to satisfy them, and ship your app. By building on standard javax.inject annotations (JSR-330), each class is easy to test. You don't need a bunch of boilerplate just to swap the RpcCreditCardService out for a FakeCreditCardService.
Dependency injection isn't just for testing. It also makes it easy to create reusable, interchangeable modules.

ButterKnife

View "injection" library for Android which uses annotation processing to generate code that does direct field assignment of your views.

Transfuse

Transfuse is a Java Dependency Injection (DI) and integration library geared specifically for the Google Android API.
There are several key features that make Transfuse a great framework to use with Android:
Dependency Injection - Transfuse implements the JSR-330 standard annotations
POJO Components - Transfuse gives users the ability to develop Android components in Plain Old Java Objects (POJO), enabling a testable, decoupled and flexible style.
Compile Time Code Generation - Transfuse is remarkably small, lightweight and fast due to the technique of generating supporting code at compile time.
Manifest Management - Transfuse manages the Android Manifest, eliminating the duplicated effort of declaring and registering components.
All of these features help eliminate boilerplate plumbing code and make Android applications much easier to write.

Which is the best Dependency Injection Framework?

It’s purely depending on the usage of your project.

For Example:
In android, if I want to avoid the boilerplate code such as injection of views, view holder in adapter and click listeners then the preferred library can be ButterKnife compare to others because remaining all done more than the required. There are tons of features which are not used added in all these libraries.

AndroidAnnotations  and ButterKnife does the similar work.
RoboGuice, Dagger and Transfuse are in the same category.

We will take one from each, say RoboGuice vs ButterKnife.

Let see, which is better for the example taken.

RoboGuice
ButterKnife
Minimum Jars required
3 (roboguice-2.0.jar, javax.inject-1.jar and guice-3.0-no_aop.jar)
1 (butterknife-4.0.1.jar)
Should replace Activity?
Yes, Replace Activity with RoboActivity
No Need
Can be used?
Yes, By adding one more jar (roboguice-sherlock-1.5) to the application and we should replace SherlockActivity to RoboSherlockActivity
Yes, No need of extra jars
Injection for Click Listeners
No
Yes
Performance
There is performance impact as it's done on runtime using reflection
Compile time
Pojo Injection
Yes
No
injection in Fragments
Yes
Yes
Injection in Adapters
No
Yes
Code License
Origin
Sample Source Code

Note: Managing Your App's Memory from developer.android

Avoid dependency injection frameworks
Using a dependency injection framework such as Guice or RoboGuice may be attractive because they can simplify the code you write and provide an adaptive environment that's useful for testing and other configuration changes. 

Be careful about using external libraries
External library code is often not written for mobile environments and can be inefficient when used for work on a mobile client.


Source Code
You can download the source code by clicking the links provided in the comparison table. This project is built using eclipse IDE. Unzip and import the project into Eclipse, it’s a good idea to use the Project by clean and rebuild from the project menu.

Thanks for reading :) 
Whether this post is helpful?


Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments.