Pages

Tuesday, 15 March 2016

A splash screen for Unity application(Only useful with personal or free edition) on Android platform

I always wanted to display my own splash screen as the first thing in my applications. And I was looking for a solution for this with
Unity personal edition. And I found one myself, well not a complete one!

With personal edition, unity displays its logo when the application is launched. You cannot suppress it from displaying
it, but what you can do is display a splash screen with your logo first and then let unity display its logo.

To accomplish this what we do is, before starting the UnityPlayerActivity we will start our activity which displays our the splash screen.

Lets go and create this activity.

To make the splash screen configurable, the splash screen activity will accept, splash screen image, splash screen duration and the activity to start once the splash screen is expired.

These configuration values needs to be specified in the AndroidManifest.xml file under the splash screen activity section.

A sample splash screen activity declaration in the manifest file is shown below,
 <activity android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:launchMode="singleTask"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    android:name="com.example.unitysplash.android.SplashScreen">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
  
  <!--
  Activity com.unity3d.player.UnityPlayerActivity will be launched once the splash screen completes
  -->
      <meta-data android:name="activityToStart" android:value="com.unity3d.player.UnityPlayerActivity" />
  
  <!--
  splash screen displays @drawable/splash_screen image resource
  this image can be kept at, <Unity Project>\Assets\Plugins\Android\res\drawable-nodpi\
  -->
  <meta-data android:name="splashImage" android:resource="@drawable/splash_screen" /> 
  
  <!-- splash screen expires after 1000 milli seconds -->
  <meta-data android:name="duration" android:value="1000" />
  
    </activity>


Path for the AndroidManifest file is <Unity Project>\Assets\Plugins\Android.

If you do not have the AndroidManifest.xml file then you can generate one if you export your project. You can export the project from build settings.
After exporting add the above activity declaration and make sure that default activity's name is changed to "com.unity3d.player.UnityPlayerActivity".

If you are using custom activity for Unity then give its name for activityToStart.

Now lets go and create the activity. We will keep our activity in a jar file, so create and android library project.

Once the project is created add the class SplashScreen which derives from Activity.

In the onCreate of this activity, first retrieve the meta-data as,
        try {
            ActivityInfo ai = getPackageManager().getActivityInfo(this.getComponentName(), PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;

            mActivityToStart = bundle.getString("activityToStart", mActivityToStart);
            mSplashImage = bundle.getInt("splashImage", mSplashImage);
            mDuration = bundle.getInt("duration", mDuration);

        } catch (PackageManager.NameNotFoundException e) {
            Log.d(SplashScreen.class.getName(), e.getMessage());
        }

Now create an ImageView and set the specified image resource to this View.
            LinearLayout layout = new LinearLayout(this);
            layout.setOrientation(LinearLayout.HORIZONTAL);

            ImageView splashImage = new ImageView(this);
            splashImage.setImageResource(mSplashImage);
            splashImage.setScaleType(ImageView.ScaleType.FIT_XY);
            layout.addView(splashImage, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            setContentView(layout, new  ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));


To handle the time-out add a Handler implementation,
    private Handler mSplashTimeoutHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == SplashTimeoutMessage) {
                try {
                    Intent i = new Intent(SplashScreen.this, Class.forName(mActivityToStart));
                    startActivity(i);
                    SplashScreen.this.finish();
                } catch (ClassNotFoundException e) {
                    Log.d(SplashScreen.class.getName(), e.getMessage());
                }
            }
            super.handleMessage(msg);
        }
    };


In the onResume post the handler with delay as the duration mentioned.
        mSplashTimeoutHandler.sendMessageDelayed(mSplashTimeoutHandler.obtainMessage(SplashTimeoutMessage), mDuration);

In case user presses the back key before the splash screen is finished do not launch the final activity. To do this implement onBackPressed as,
        mSplashTimeoutHandler.removeMessages(SplashTimeoutMessage);

Now we are done with SplashScreen activity. Now create a jar out of it and copy it to <Unity Project>\Assets\Plugins\Android

Now if you launch the application splash screen should be the first activity displayed.


Please find a complete example at https://github.com/trsquarelab/unityexamples/tree/master/UnitySplashScreen

Wednesday, 9 March 2016

Advanced Android Interview Questions and Answers 4


1. Describe a scenario where an Activity enters pause state but not stop state?

SHOW/HIDE ANSWER
When a semi-transparent activity opens making the previous activity partially visible.
Reference
http://developer.android.com/training/basics/activity-lifecycle/pausing.html

2. What kind of actions are suggested to perform on onPause callback of an Activity implementation?

SHOW/HIDE ANSWER
  • Stop animations or other ongoing actions that could consume CPU
  • Possibly commit unsaved changes
  • Release system resources such as broadcast receivers, handles to camera, sensors, etc.
Reference
http://developer.android.com/training/basics/activity-lifecycle/pausing.html

3. Describe a scenario where onRestart will be called for an Activity implementation?

SHOW/HIDE ANSWER
User launches a new activity B from activity A. And then the user presses back button on activity B.
Here onStop will be called for activity A when user launched activity B. Once user presses back button on activity B, onRestart, onStart and onResume callback are called for activity A.

The onRestart() method, however, is called only when the activity resumes from the stopped state.
Reference
http://developer.android.com/training/basics/activity-lifecycle/stopping.html

4. Describe some of the scenario where an activity could possibly be destroyed?

SHOW/HIDE ANSWER
  • User presses back button
  • finish() method is called for the Activity
  • The Activity is inactive for long time
  • Foreground Activity requires more resources so the system must shut down background processes to recover memory
Reference
http://developer.android.com/training/basics/activity-lifecycle/recreating.html

5. What are some of the advantages of Fragments?

SHOW/HIDE ANSWER
Fragments allows us to modularize the Activity.
Fragments helps us in splitting up views for some devices(phone, tablets) or based on orientations(landscape, portrait).
Fragments helps us to create reusable views.
Reference
http://developer.android.com/training/basics/fragments/index.html

6. What is AIDL?

SHOW/HIDE ANSWER
AIDL stands for Android Interface Definition Language and is used to define the programming interface that the client and server uses to communicate with each other using (IPC).
Following data types are supported by AIDL,
  • primitive types : int, long, char, boolean, etc.
  • String
  • CharSequence
  • List
  • Map
Reference
http://developer.android.com/guide/components/aidl.html

7. What are some of the cases that you would need to handle when using AsyncTask?

SHOW/HIDE ANSWER
Screen rotation : Suppose the device is rotated then the Activity will be recreated making the reference to the Activity invalid. This would even cause memory leaks as the AsyncTask might have a reference to the Activity or worse Views or the AsyncTask is implemented as a nested class of the Activity.
Activity is destroyed: This is very similar to the first one, AsyncTask continues to execute even if the Activity is destroyed.
Need to explicitly implement the cancel logic : If AsyncTask.cancel() is called then AsyncTask.isCancelled() returns true and developer is supposed to handle the AsyncTask.isCancelled() being true case.
By default AsyncTasks has just one worker thread

8. What are the contents of an APK file?

SHOW/HIDE ANSWER
APK(Android application package) is the file format used by Android for distributing and installing apps and software component.
Some of the contents of APK file are,
  • Manifest file in its binary format
  • Certificate of the application
  • Library files for different platform(armeabi, armeabi-v7a, x86, etc)
  • Compiled resource files
  • Asset files
  • classes.dex : Classes compiled in dex file format

9. What are some of the features introduced in Android N?

SHOW/HIDE ANSWER
  • Multi-window support - Users can now open two apps on the screen at once.
  • Notification enhancements - Bundled notifications, Direct reply, Custom views, Template updates
  • Improvement in Doze mode - Doze mode applied in two phases. Any time the screen is off for a period of time and the device is unplugged, Doze applies a subset of the familiar CPU and network restrictions to apps. When the device is stationary again, with screen off and on battery for a period of time, Doze applies the full CPU and network restrictions on PowerManager.WakeLock, AlarmManager alarms, and GPS/Wi-Fi scans.
  • Vulkan API - New graphics API from Khronos Group
  • Quick Settings Tile API
  • Number-blocking - Supports number blocking in the platform itself and provides a framework API to let service providers maintain a blocked-number list.
  • Call screening - CallScreeningService introduced to screen incoming calls.
  • Direct boot - Improved device startup time. Rather than at first boot, apps are compiled Just-in-Time the first time you launch them.
Reference
http://developer.android.com/preview/api-overview.html

10. What are some of the features introduced in Android Marshmallow?

SHOW/HIDE ANSWER
  • Runtime Permissions
  • Doze and App Standby
  • BoringSSL
  • Notifications - Removed method Notification.setLatestEventInfo and introduced Notification.Builder
Reference
http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html

11. What are some of the features introduced in Android Lollipop?

SHOW/HIDE ANSWER
  • Material design
  • Android Runtime (ART) - ART runtime replaces Dalvik as the platform default.
  • Platform support for 64-bit architectures
  • Notifications - Notifications now appear on the user's lock screen, heads-up notification (a small floating window that allows the user to respond or dismiss without leaving the current app)
Reference
http://developer.android.com/about/versions/android-5.0-changes.html

Tuesday, 8 March 2016

Advanced Android Interview Questions and Answers 2


1. What is dependency injection?

SHOW/HIDE ANSWER
Is a pattern for resolving dependency. It is an implementation of dependency inversion principle (DIP). Some of the libraries to enable dependency injection for are,
  • AndroidAnnotations
  • Butter Knife
  • Dagger
  • Dagger2
  • RoboGuice

2. How to set permission for content provider?

SHOW/HIDE ANSWER
Read-write permission can be set in the attribute android:permission of provider tag
Read permission can be set in android:readPermission
Write permission can be set in android:writePermission
URI level permission can be set using path-permission tag
Use android:grantUriPermissions to grant temporary permission
Reference
http://developer.android.com/guide/topics/providers/content-provider-creating.html#Permissions

3. What are the different protection levels in permission?

SHOW/HIDE ANSWER
  • normal : The default value, is automatically granted at installation time
  • dangerous : Displays it to the user at installation/run-time for their confirmation
  • signature : Grants if the requesting application is signed with the same certificate as the application that declared the permission
  • signatureOrSystem : Grants if installed in the system image or signature(c)
Reference
http://developer.android.com/guide/topics/manifest/permission-element.html

4. What is a ViewStub?

SHOW/HIDE ANSWER
A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime.
When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated. The ViewStub then replaces itself in its parent with the inflated View or Views.
Therefore, the ViewStub exists in the view hierarchy until setVisibility(int) or inflate() is invoked.
Reference
http://developer.android.com/reference/android/view/ViewStub.html

5. What is the use of merge tag in layout?

SHOW/HIDE ANSWER
merge tag can be used for optimizing the layout. When a layout is included in another one; it is useful in removing unnecessary layout that are just used to wrap views. Reference
http://developer.android.com/training/improving-layouts/reusing-layouts.html#Merge

6. Which is the best place to register and unregister a BroadcastReceiver from an Activity?

SHOW/HIDE ANSWER
onStart and onStop respectively

7. What is the difference between DVM(Dalvik Virtual Machine) and JVM(Java Virtual Machine)?

SHOW/HIDE ANSWER
DVM is register based and is designed to run on low memory devices.
JVM is stack based. The main objective when JVM was designed is to make it run as many platform as possible.
DVM requires less instruction set.
.dex file which DVM can understand is lesser in size compared to .class files.

8. What is a 9 patch image?

SHOW/HIDE ANSWER
Is a stretchable image that helps in solving compatibility issues when used with devices with different screen sizes.
Here an image is divided into 9 parts,
4 corners - Do not scale
2 vertical edges - Scale vertically
2 horizontal edges - Scale horizontally
1 Middle area - Scale vertically and horizontally
Reference
http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

9. Under what license Android is released?

SHOW/HIDE ANSWER
Android is released under Apache Software License, Version 2.0("Apache 2.0"). Linux kernel patches are under the GPLv2 license. Reference
https://source.android.com/source/licenses.html

10. What is a SparseArray?

SHOW/HIDE ANSWER
SparseArrays are used to map integers to Objects. It is called sparse because there can be gaps in the indices.
It is intended to be more memory efficient than using a HashMap to map Integers to Objects, both because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping. Reference
http://developer.android.com/reference/android/util/SparseArray.html

11. What is an ArrayMap?

SHOW/HIDE ANSWER
ArrayMap is a generic key->value mapping data structure that is designed to be more memory efficient than a traditional HashMap.
It keeps its mappings in an integer array of hash codes for each item, and an Object array of the key/value pairs.
ArrayMap uses binary search on the integer array to find a key.
Reference
http://developer.android.com/reference/android/util/ArrayMap.html

12. What is Autoboxing?

SHOW/HIDE ANSWER
Is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes, such as int and Integer Reference
https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

13. How memory trimming can be done in Android?

SHOW/HIDE ANSWER
Implement ComponentCallbacks2, register it using registerComponentCallbacks on your Activity, Service, ContentProvider, or Application and listen for onTrimMemory callback.
onTrimMemory is called with different memory levels some of them are,
TRIM_MEMORY_RUNNING_MODERATE : The device is beginning to run low on memory
TRIM_MEMORY_RUNNING_LOW : The device is running much lower on memory
TRIM_MEMORY_RUNNING_CRITICAL : The device is running extremely low on memory
Reference
http://developer.android.com/reference/android/content/ComponentCallbacks2.html

14. What is StrictMode?

SHOW/HIDE ANSWER
StrictMode is a developer tool that can be used to detect accidental disk or network access on the application's main thread.
?
1
2
3
4
5
6
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
Reference
http://developer.android.com/reference/android/os/StrictMode.html

15. What are the ways of optimizing layout?

SHOW/HIDE ANSWER
Use Tools(Hierarchy Viewer/Lint) to measure and identifying the bottleneck
Change deeper layouts to flat or wide
Use ViewStub for displaying On Demand
Reference
http://developer.android.com/training/improving-layouts/index.html

16. How to optimize ListView?

SHOW/HIDE ANSWER
  • Use background thread to load ListView data
  • User View Holder pattern
You may also want to try RecyclerView References
http://developer.android.com/training/improving-layouts/smooth-scrolling.html http://blog.trsquarelab.com/2015/12/introduction-to-android-recyclerview.html

17. What is RecyclerView?

SHOW/HIDE ANSWER
RecyclerView can be used to display large data much like ListView.
In RecyclerView we can set custom layout management for its children's, it has animation support built-in, has item decorator support and it uses the View-holder pattern.
Reference
http://blog.trsquarelab.com/2015/12/introduction-to-android-recyclerview.html

18. What is JobScheduler?

SHOW/HIDE ANSWER
An API for scheduling jobs against the framework that will be executed in your application's own process and in main thread. To use job JobScheduler,
  • Create a JobServer implementation: by extending JobService
  • Create JobInfo : Use JobInfo.Builder
  • Get the JobScheduler : Context.getSystemService(Context.JOB_SCHEDULER_SERVICE)
  • schedule the job : JobScheduler.schedule
Reference
http://developer.android.com/reference/android/app/job/JobScheduler.html http://developer.android.com/reference/android/app/job/JobService.html http://developer.android.com/reference/android/app/job/JobInfo.html

19. How to create application that support different languages?

SHOW/HIDE ANSWER
create additional values directories inside res/ that include a hyphen and the ISO language code at the end of the directory name.
Keep the language specific string resources into the corresponding directory.
MyProject/
    res/
       values/
           strings.xml
       values-es/
           strings.xml
       values-fr/
           strings.xml
Reference
http://developer.android.com/training/basics/supporting-devices/languages.html

20. How to create application that support different screen sizes?

SHOW/HIDE ANSWER
Create different layout folder according to the screen sizes.
MyProject/
    res/
        layout/              # default (portrait)
            main.xml
        layout-land/         # landscape
            main.xml
        layout-large/        # large (portrait)
            main.xml
        layout-large-land/   # large landscape
            main.xml
  
Create different bitmaps according to the screen densities.
MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png
Reference
http://developer.android.com/training/basics/supporting-devices/screens.html

Saturday, 5 March 2016

auto and decltype in C++11 and C++14

C++11 and C++14 compiler helps you to find out the type of a variable, function with the introduciton of auto. auto works similar to var in C#.

auto with declarations

So instead of declaring
    int x = 10;
you can declare
    auto x = 10; 

Can we use auto without initialization? No. In this case compiler will not be able to deduce the type of the variable.

Can we use auto with class member  variable? Only where you can initialize the member variable; static constants. So the below shown declaration is valid.
    class Test
    {
    public:
        static const auto x = 4;
    };

auto with functions

In C++11

Another place where we can use auto is with function return type. But there is a catch in using auto with return type. If you just use as shown below things will not work,
    auto add(int x, int y) {
        return x+y;
    }

You can definitely use auto in place of function return type, if you change the function to as shown below,
    auto add(int x, int y) -> int {
        return x+y;
    }

This doesn't look like too interesting, isn't it; it is just that we are specifying the return type in a different place. We will see some use of having auto with function declaration in c++11 in below sections

In C++14

In C++14 the first version of add function defined above will work fine.

What if we have multiple return statement with different types? you will get a compilation error. So the following function will give you compilation error.
auto factorial(int n) 
{
    if (n == 1) {
        return int(1);
    }
    if (n == 2) {
        return long(2);
    }

    int res = 1;
    for (; n>0; --n) {
        res *= n;
    }

    return res;
}

What about the following recursive function? 
auto factorial(int n) 
{
    if (n > 1) {
        return factorial(n-1) * n;
    }

    return 1;
}

Another compilation error. It is not allowed to call recursive function call before a return statement.
So change the function slightly as shown below and everything should start working.
auto factorial(int n) 
{
    if (n == 1) {
        return 1;
    }
    return factorial(n-1) * n;
}

In c++14 you can also make function parameter auto, the below given version of factorial works just fine in c++14.
auto factorial(auto n)
{
    if (n == 1) {
        return 1;
    }
    return factorial(n-1) * n;
}

decltype

Let me introduce another feature, decltype,  and see if the auto in function return type has any benefit or not.
decltype helps to get the type of a variable or expression, one use of it is shown below,
    float a = 1.0f;
    decltype(a) b = a;

Ok so we have got another way to declare variable. We can use auto as well in this case, what benefit does decltype brings?
Now lets go back the function that we declared and see if we can use decltype there, maybe we can. Modified function is shown below,
    auto add(int x, int y) -> decltype(x) {
        return x+y;
    }
Another interesting thing about decltype is that we can also give expression with it. The following code  snippet works really well and the return type will be float.
    auto add(float x, int y) -> decltype(x+y) {
        return x+y;
    }

Like sizeof operator the expression in decltype will not  be getting evaluated. So the following program will output 1,1.
    #include <iostream>

int main(int argc, char **argv) {
    int x = 1;
    decltype(++x) y = x;
    std::cout << x << "," << y<< std::endl;
}   

auto with reference

Now lets see how auto works with references, can you guess what is the output of the following code block?
#include <iostream>
    
int & incr(int &x)
{
    return ++x;
}

int main(int argc, char **argv) {
    int x = 1;
    auto y = incr(x);
    ++y;
    std::cout << x << std::endl;
}

It is 2 not 3. auto type by default takes the value not reference. Change the declaration as shown below and everything should work as expected.
    auto & y = incr(x);

Then what about pointers?auto works as expected, it is not necessary to specify as auto *

decltype(auto) - c++14

The above code can be made to work as expected using  decltype(auto), It takes the type from the initialization

#include <iostream>

int & incr(int &x)
{   
    return ++x;
}   

int main(int argc, char **argv) {
    int x = 1;
    decltype(auto) y = incr(x);
    ++y;
    std::cout << x << std::endl;
}  

Output of the above program is 3.

Now lets change the function incr function by using auto as shown below and lets see what happens.
#include <iostream>

auto incr(int &x)
{   
    return ++x;
}   

int main(int argc, char **argv) {
    int x = 1;
    decltype(auto) y = incr(x);
    ++y;
    std::cout << x << std::endl;
} 
Now the output is 2.

How do we fix this to make the behaviour same as that of the first program? One way is to use decltype(auto) with function as shown below,
#include <iostream>

decltype(auto) incr(int &x)
{   
    return ++x;
}   

int main(int argc, char **argv) {
    int x = 1;
    decltype(auto) y = incr(x);
    ++y;
    std::cout << x << std::endl;
}  

Please visit http://blog.trsquarelab.com/2015/05/compiling-c11-and-c14-programs-with-gcc.html for information on how to compile with C++11 and C++14 support in Ubuntu using GCC

lambda expression in C++11 and C++14

Lambda expressions are available from C++11 onwards.

The simplest of the lambda expression is
[] {};
which does nothing.

The syntax of a lambda expression is,
[ /*capture-list*/ ] ( /*params*/ ) mutable /* optional*/ /*exception*/ /*attribute*/ -> /*return type*/ { /*body*/ }
capture-list list of comma separated captures
params list of comma separated parameters
mutable allows body to modify parameters captured by value
exception exception specifications
attribute attribute specifications

You can think of lambda expression as a functor. For easy understanding you can imagine that the lambda expression is implemented as some thing like,
class ClosureType
{
    /* members variables are identified using capture list */
public:
    ClosureType(/*capture list*/)
    {}

    /* non-mutable lambda */
    return-type operator(/* parameter list*/) const {/*body*/}

    /* mutable lambda */
    return-type operator(/* parameter list*/) {/*body*}
};

Simple examples

The following code snippet will print Hello from Lambda
[]{
    std::cout << "Hello from Lambda" << std::endl;
}();

Capture list

To access variables declared outside the lambda expression you can use capture list.
int n = 10;

[n]{
    std::cout << "n = " << n << std::endl;
}();
Capturing all automatic variables,
int n = 10;
int m = 20;

[=]{
    std::cout << "n = " << n << " m = " << m << std::endl;
}();
No need to capture global variables, they are accessible in lambda expressions. The above method access variables by value.

To access by reference use & as shown below,
    int n = 10;
    int m = 20;

    [n, &m]{
        std::cout << "n = " << n;
        m = 10;
    }();


    std::cout << " m = " << m << std::endl;
Output of the above program is n = 10 m = 10

Just as we done earlier use just & to access all automatic variables by reference.

this variable can be accessed in the lambda expressions if we add this in the capture list as [this].

capture expressions - C++14

C++14 allows captured members to be initialized with arbitrary expressions. A simple example would be,
auto l = [v = 1] {std::cout << v; };
l();
We can also use reference in the expression as,
int y;
[&x = y]{}

 

Parameters

Paremeters can be specified as you would do for a function. For example the following code will output 1, 2
auto l = [] (int a, int b) {std::cout << a << " " << b; };
l(1, 2);
Can I use template like I do with function? No. But in C++14 you can use auto for parameters as shown below,
auto l = [] (auto a) {std::cout << a ; };
l(1);

 

Return value

If you do not specify any return type will be deduced from the return statement,
auto increment = [] (int i) {return ++i;};
std::cout << increment(1) << std::endl;
The above code can also be declared as,
auto increment = [] (int i) ->int {return ++i;};
std::cout << increment(1) << std::endl;
We can also use decltype in return type.
auto increment = [] (int i) ->decltype(i) {return ++i;};
std::cout << increment(1) << std::endl;
In C++14 the return type can also be auto

Recursive lambda expression

We can also have recursion with lambda expression. In this case we cannot use auto to store lambda variable, but fill have to use std::function. An example is shown below,
#include <iostream>
#include <functional>

std::function<int(int)> factorial = [] (int n) -> int {
    if (n <= 1) {
        return 1;
    }

    return factorial(n-1) * n;
};

int main(int argc, char ** argv)
{
    std::cout << factorial(4) << std::endl;
    return 0;
}

Nested lambda expression

Lambda expression can also be nested.
#include <iostream>

int main(int argc, char ** argv)
{
    int i = 1;

    auto outer = [=] {
        int j = 2;
        auto inner = [=] {
            std::cout << "inner : " << i << " " << j;
        };
        inner();
        std::cout << "outer : " << i << " " << j;
    };

    outer();

    return 0;
}
Output of the above program is inner : 1 2outer : 1 2

Lambda expression as function parameter

There are many ways of declaring function which takes lambda expression as parameter, some of them are shown below.
#include <iostream>
#include <functional>

void func1(std::function<void(std::string const &)> const & l)
{
    l("from func1");
}

template <typename T>
void func2(T l)
{
    l("from func2");
}

// if C++14 is supported
#if __cplusplus > 201103L
void func3(auto l)
{
    l("from func3");
}
#endif

int main(int argc, char **argv)
{
    auto l = [] (std::string const & msg) {
                    std::cout << msg << std::endl;
                };

    func1(l);
    func2(l);

#if __cplusplus > 201103L
    func3(l);
#endif

    return 0;
}

Function returning lambda expression

Examples for function returning lambda expressions are given below,
#include <iostream>
#include <functional>

std::function<void()> func1()
{
    return [] {
                std::cout << "from func1" << std::endl;
              };
}

// In C++14 you don't have to specify return type
auto func2() -> std::function<void()>
{
    return [] {
                std::cout << "from func2" << std::endl;
              };
}

int main(int argc, char **argv)
{
    func1()();
    func2()();

    return 0;
}

Dangling reference

We have to make sure that the variables captured using reference is alive (life time is not ended).
As an example the below given programme has an illegal memory access. It is trying to access variable i after its life time is over.
#include <iostream>
#include <functional>

std::function<void()> func()
{
    int i = 10;
    return [&] {
                std::cout << i << std::endl;
              };
}

int main(int argc, char **argv)
{
    func()();

    return 0;
}

Sizeof lambda expressions

Size of lambda expressions might vary according to the compiler. If the lambda expression does not capture any variables then its size will mostly be 1. If it captures variables the size of lambda expression will the total size of the variables it captured. The output of the below program when compiled with gcc is 1 8.
#include <iostream>

int main(int argc, char ** argv)
{
    int i = 1;
    int j = 2;

    auto l1 = [] {
        std::cout << "l1";
    };

    auto l2 = [=] {
        std::cout << "l2 : " << i << j;
    };

    std::cout << sizeof(l1) << " " << sizeof(l2) << std::endl;

    return 0;
}

Please visit http://blog.trsquarelab.com/2015/05/compiling-c11-and-c14-programs-with-gcc.html for information on how to compile with C++11 and C++14 support in Ubuntu using GCC

multi-threaded programming in C++11

This page is more on examples of multi-thread programming in c++11 than a reference.

Creating thread

A new thread can be created using std::thread class. An example is shown below on how to create a thread.
#include <thread>
#include <iostream>

void run() 
{
    std::cout << __FUNCTION__ << std::endl;
}

int main(int argc, char **argv) {
    std::thread t(run);

    t.join();
}

The above example create a thread t which executes the run function it the new thread.
If we do not create any thread there will always be one thread in the application, we usually call it the main thread.Now suppose we are creating a new thread then the main thread and the newly created thread will execute in parallel. In our example above thread object t is created in main thread and it will be out of scope once main thread finish executes main function and terminate will be called, even if the newly created thread is active. To avoid this we need to make our main thread wait for the newly created thread to complete its execution. The way to do that is to call t.join();

Important functions in std::thread

get_id Retrieves thread thread id
joinable Checks if the thread is joinable
join Joins the thread, ie. wait for the thread to complete its execution
detach Detach thread
swap Swap thread objects

Using Mutex

Mutex can be used to protect data from multiple threads. mutex::lock can be used to prevent multiple thread access to shared data and mutex::unlock to release the lock.
An example of using std::mutex is shown below,
#include <thread>
#include <mutex>
#include <chrono>
#include <vector>
#include <memory>
#include <iostream>

void run()
{
    static std::mutex m;

    // only one thread at a time so that both
    // of the print outs happens one after another
    m.lock();

    std::cout << __FUNCTION__ << " started" << std::endl;

    // wait for 100 milli seconds
    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    std::cout << __FUNCTION__ << " ended" << std::endl;

    m.unlock();
}

int main(int argc, char **argv) {
    std::vector<std::shared_ptr<std::thread> > threads;

    for (int i=0; i<5; ++i) {
        std::shared_ptr<std::thread> t(new std::thread(run));
        threads.push_back(t);
    }

    for (std::shared_ptr<std::thread> t : threads ) {
        t->join();
    }
}

Important functions in std::mutex

lock locks the mutex
unlock unlock the mutex
try_lock try locking the mutex, returns if the mutex is already locked

Condition Variable

Condition variable is a synchronization primitive that allows a thread to wait until a condition occurs.
As a simple example, lets take the first example and make it work without using join function.
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>

std::condition_variable cv;
std::mutex m;

void run() {
    std::cout << __FUNCTION__ << " entered" << std::endl;

    // lets put a small delay
    for (int i=0; i<5; ++i) {
        std::cout << "." << std::flush;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    std::cout << std::endl;

    std::cout << __FUNCTION__ << " exiting" << std::endl;

    // notify once we are done with the thread execution
    std::unique_lock<std::mutex> l(m);
    cv.notify_one();
}

int main() {
    std::thread t(run);
    t.detach();

    // wait for the thread to finish, once the thread execution is complete it will be notified 
    std::unique_lock<std::mutex> l(m);
    cv.wait(l);
    
    return 0;
}

Important functions in std::condition_variable

wait wait for notification
notify_one notify one waiting thread
notify_all notify all waiting thread

Now lets see some example of multi thread programming.

Printing 1 to 10 from two thread.

Lets print 1 to 10 with odd numbers printed in one thread and even from the other thread.
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>

// mutex used with condition variables
std::mutex evenMutex;
std::mutex oddMutex;

// condition variables
std::condition_variable evenCV;
std::condition_variable oddCV;

void evenThread()
{
    for (int i=2; i<11; i+=2) {
        // wait for the odd thread to print the value and notify this thread
        {
            std::unique_lock<std::mutex> l(oddMutex);
            oddCV.wait(l);
        }

        std::cout << i << std::endl;

        // notify the odd thread to print value
        std::unique_lock<std::mutex> el(evenMutex);
        evenCV.notify_one();
    }
}

void oddThread()
{
    for (int i=1; i<10; i+=2) {
        std::cout << i << std::endl;

        // notify the even thread to print the value
        {
            std::unique_lock<std::mutex> ol(oddMutex);
            oddCV.notify_one();
        }

        // wait for the even thread to print the value
        std::unique_lock<std::mutex> el(evenMutex);
        evenCV.wait(el);
    }
}

int main(int argc, char **argv)
{
    std::thread ot(oddThread);
    std::thread et(evenThread);

    ot.join();
    et.join();

    return 0;
}

Thread pool 

Lets create a thread pool which creates a given number of threads and distributes the work in one of the available thread. If no thread is available it will wait for a thread to finish.
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <vector>
#include <queue>
#include <memory>

class ThreadPool;

// worker class. It will create a thread and wait for a task from the ThreadPool
class Worker {
    std::thread mThread;
    std::atomic_bool mFinished;
    ThreadPool *mPool;

public:
    Worker(ThreadPool *pool)
     : mFinished(false),
       mPool(pool) {
        create();
    }

    ~Worker() {
        join();
    }

    void join() {
        if (mThread.joinable()) {
            mThread.join();
        }
    }

    void terminate() {
        mFinished = true;
    }

    void create();

private:
    void doCreate();
};

class ThreadPool {
private:
    int mWorkerCount;
    // worker vector
    std::vector<std::shared_ptr<Worker>> mThreads;

    // work quueue is a queue of lambda functions
    std::queue<std::function<void(void)>> mWorkQueue;

    // lock used to synchronize queue access and update
    std::mutex mWorkQueueLock;

    // condition variable used to notify task availability
    std::mutex mNotifierLock;
    std::condition_variable mNotifier;

    // condition variable used to notify termination of thread pool
    std::mutex mTerminateLock;
    std::condition_variable mTerminateCV;

public:
    ThreadPool(int workerCount)
     : mWorkerCount(workerCount) {
        create();
    }

    ~ThreadPool() {
        // wait for the termination of the pool
        std::unique_lock<std::mutex> tl(mTerminateLock);
        mTerminateCV.wait(tl);
    }

    void terminate() {
        for (std::shared_ptr<Worker> t: mThreads) {
            t->terminate();
        }
        std::unique_lock<std::mutex> tl(mTerminateLock);
        mTerminateCV.notify_one();
    }

    void submitWork(std::function<void()> const & work) {
        // add task to queue
        {
            std::unique_lock<std::mutex> ql(mWorkQueueLock);
            mWorkQueue.push(work);
        }

        // notify availability of task
        std::unique_lock<std::mutex> nl(mNotifierLock);
        mNotifier.notify_one();
    }

    std::function<void()> getWork() {
        // wait for a task
        waitForWork();

        {
            // retrieve a work
            std::unique_lock<std::mutex> ql(mWorkQueueLock);
            std::function<void()> work = mWorkQueue.front();
            mWorkQueue.pop();
            return work;
        }
    }

private:
    void waitForWork() {
        // wait until queue is not empty
        std::unique_lock<std::mutex> nl(mNotifierLock);
        mNotifier.wait(nl, [this] {
            std::unique_lock<std::mutex> ql(mWorkQueueLock);  return !mWorkQueue.empty();
        });
    }

    void create() {
        for (int i=0; i<mWorkerCount; ++i) {
            mThreads.push_back(std::shared_ptr<Worker>(new Worker(this)));
        }
    }

};

void Worker::create() {
    mThread = std::thread([this] {
        doCreate();
    });
}

void Worker::doCreate() {
    while (!mFinished) {
        mPool->getWork()();
    }
}

int main(int argc, char **argv) {
    ThreadPool pool(2);

    pool.submitWork([]{std::cout << "**work1**" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); });
    pool.submitWork([]{std::cout << "**work2**" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); });
    pool.submitWork([]{std::cout << "**work3**" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); });
    pool.submitWork([]{std::cout << "**work4**" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); });
    pool.submitWork([]{std::cout << "**work5**" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); });
    pool.submitWork([]{std::cout << "**work6**" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); });

    return 0;
}

Advanced Android Interview Questions and Answers 3

(PREVIOUS (Advanced Android Interview Questions and Answers 2

1. How to verify that there is an activity available that can respond to the intent?

SHOW/HIDE ANSWER
Using package manager.
PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(intent,
        PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0;

2. How to get result from an Activity?

SHOW/HIDE ANSWER
Call startActivityForResult() with a request code
Implement onActivityResult(int requestCode, int resultCode, Intent data) on your activity
A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the user backed out or the operation failed for some reason

3. What is the use of android:sharedUserId?

SHOW/HIDE ANSWER
If android:sharedUserId is set same for two applications which are signed with the same certificate then both the application will share the same user ID.
Application with the same user ID can access each other's data and, if desired, run in the same process.

4. How to convert an Android application project to an Android library project with gradle build system?

SHOW/HIDE ANSWER
In your app build.gradle file change,
apply plugin: 'com.android.application'
to
apply plugin: 'com.android.library'
For a libary project you wont need applicationId, versionCode and versionName

5. What is the purpose of running zipalign?

SHOW/HIDE ANSWER
Running zipalign ensure that all uncompressed data(images or raw files) starts with a particular alignment(4-byte boundaries) relative to the start of the file.
The benefit is a reduction in the amount of RAM consumed when running the application.
Reference
http://developer.android.com/tools/help/zipalign.html

6. What is the purpose of running ProGuard?

SHOW/HIDE ANSWER
The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. Benefits are,
  • smaller sized .apk file
  • more difficult to reverse engineer.

Reference
http://developer.android.com/tools/help/proguard.html

7. What is lint tool?

SHOW/HIDE ANSWER
Is a static code analysis tool that checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.
Reference
http://developer.android.com/tools/help/lint.html

8. What is multiple APK support in Google play

SHOW/HIDE ANSWER
A Feature on Google Play that allows you to publish different APKs for your application that are each targeted to different device configurations.
Reference
http://developer.android.com/google/play/publishing/multiple-apks.html

9. What is the current size limit for an application in Google play?

SHOW/HIDE ANSWER
100 MB at the time of writting this answer.

10. How to upload apks with a size of more than that is mentioned above?


11. What is Support Library?

SHOW/HIDE ANSWER
A set of code libraries that provide backward-compatible versions of Android framework APIs as well as features that are only available through the library APIs.
Reference
http://developer.android.com/intl/ja/tools/support-library/index.html

12. What is DDMS?

SHOW/HIDE ANSWER
Is a debugging tool its full name is Dalvik Debug Monitor Server (DDMS).
It some of the features are,
  • provides heap usage for a process
  • tracks memory allocation of objects
  • provides thread information
  • android file system exploring
  • method profiling
  • network trafic analysis
  • emulates phone operation and location

Reference
http://developer.android.com/intl/ja/tools/debugging/ddms.html

13. What is the differece between Serializable and Parcelable?

SHOW/HIDE ANSWER
Serializable is a standard Java interface where as Parcelable is an Android specific interface.
Parcelable is faster than Serializable. Serializable is easier than a Parcelable to implement.

14. What are the different ways to store data?

SHOW/HIDE ANSWER
  • Sqlite Database
  • Internal Store
  • External Store
  • Network Connection
  • Shared Preferences

15. What are different ways to process a task in a background thread(other than main(UI) thread) in Android?

SHOW/HIDE ANSWER
  • Using Java Thread/Runnable classes
  • Using AsyncTask
  • Using Loaders(AsyncTaskLoader, etc.)
  • Using HandlerThread/Looper/Handler
  • Using ThreadPool : http://developer.android.com/training/multiple-threads/run-code.html
  • Using IntentService

16. What is data binding?

SHOW/HIDE ANSWER
It helps in binding values of an object directly to views in the layout. If the data changes it can update the views.
Reference
http://developer.android.com/tools/data-binding/guide.html

17. What causes an ANR?

SHOW/HIDE ANSWER
  • No response to an input event (such as key press or screen touch events) within 5 seconds.
  • A BroadcastReceiver hasn't finished executing within 10 seconds.

Reference
http://developer.android.com/training/articles/perf-anr.html

18. In which thread does an IntentService performs it's task?

SHOW/HIDE ANSWER
Not in the main thread but in a worker thread

19. What is doze mode?

SHOW/HIDE ANSWER
Device enters doze mode if, an user leaves it unplugged and stationary for a period of time, with the screen off. In doze mode network access and and CPU-intensive services are restricted.
Periodically, the system exits Doze for a brief time to let apps complete their deferred activities.
Systems exits doze mode if user wakes the device by moving it, turning on the screen, or connecting a charger.

Reference
http://developer.android.com/training/monitoring-device-state/doze-standby.html

20. What is App Standby?

SHOW/HIDE ANSWER
An application goes to App Standby mode if the user does not touch the app for certain period of time and none of the following conditions happened:
  • you explicitly launch the app
  • The app has a process currently in the foreground
  • The app produces a notification

When in standby mode, network access and background sync jobs are restricted.
When user plugs the device into a power supply, system releases apps from standby mode.

Reference
http://developer.android.com/training/monitoring-device-state/doze-standby.html