Friday 16 December 2016

Code Standand

  • Bad coding
  • Not following standard
  • Not keeping performance in mind
  • History, Indentation, Comments are not appropriate.
  • Readability is poor
  • Open files are not closed
  • Allocated memory has not been released
  • Too many global variables.
  • Too much hard coding.
  • Poor error handling.
  • No modularity.
  • Repeated code.

Thursday 15 December 2016

Secure An adroid app

https://code.tutsplus.com/articles/how-to-secure-an-android-app--cms-26385

Tuesday 13 December 2016

Activity And FragmentActivity

FragmentActivity is a subclass of Activity that was built for the Android Support Package.
The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.


  1. Fragment is a part of an activity, which contributes its own UI to that activity. Fragment can be thought like a sub activity. Where as the complete screen with which user interacts is called as activity. An activity can contain multiple fragments.Fragments are mostly a sub part of an activity.
  2. An activity may contain 0 or multiple number of fragments based on the screen size. A fragment can be reused in multiple activities, so it acts like a reusable component in activities.
  3. A fragment can't exist independently. It should be always part of an activity. Where as activity can exist with out any fragment in it.

Wednesday 7 December 2016

Run other Thread in Main Thread

Make sure that your background worker threads have access to a Context object (can be the Application context or the Service context). Then just do this in the background worker thread:
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
mainHandler.post(myRunnable);

Gladle



Gradle is an automated build toolkit that allows the way in which projects are built to be configured and managed through a set of build configuration files. This includes defining how a project is to be built, what dependencies need to be fulfilled for the project to build successfully and what the end result (or results) of the build process should be. The strength of Gradle lies in the flexibility that it provides to the developer. The Gradle system is a self-contained, command-line based environment that can be integrated into other environments through the use of plug-ins. In the case of Android Studio, Gradle integration is provided through the appropriately named Android Studio Plug-in.
Although the Android Studio Plug-in allows Gradle tasks to be initiated and managed from within Android Studio, the Gradle command-line wrapper can still be used to build Android Studio based projects, including on systems on which Android Studio is not installed.
The configuration rules to build a project are declared in Gradle build files and scripts based on the Groovy programming language.


http://www.techotopia.com/index.php/An_Overview_of_Gradle_in_Android_Studio

Tuesday 6 December 2016

how to check memory leak





The Memory Monitor in Android Studio shows you how your app allocates memory over the course of a single session. The tool shows a graph of available and allocated Java memory over time, including garbage collection events. You can also initiate garbage collection events and take a snapshot of the Java heap while your app runs. The output from the Memory Monitor tool can help you identify points when your app experiences excessive garbage collection events, leading to app slowness.
For more information about how to use Memory Monitor tool, see Viewing Heap Updates.

http://www.vogella.com/tutorials/EclipseMemoryAnalyzer/article.html


Tracking memory allocations can give you a better understanding of where your memory-hogging objects are allocated. You can use Allocation Tracker to look at specific memory uses and to analyze critical code paths in an app such as scrolling.

Although it is not necessary or even possible to remove all memory allocations from your performance-critical code paths, Allocation Tracker can help you identify important issues in your code. For example, an app might create a new Paint object on every draw. Making the Paint object global is a simple fix that helps improve performance.
  1. Start your app on a connected device or emulator.
  2. In Android Studio, select View > Tool Windows > Android Monitor.
  3. In the upper-left corner of Android Monitor, select the Monitors tab.
  4. In the Memory Monitor tool bar, click Allocation Tracker  to start memory allocations.
  5. Interact with your app.
  6. Click Allocation Tracker  again to stop allocation tracking.
    Android Studio creates an allocation file with the filename application-id_yyyy.mm.dd_hh.mm.alloc, opens the file in Android Studio, and adds the file to the Allocations list in the Captures tab.
  7. In the allocations file, identify which actions in your app are likely causing too much allocation and determine where in your app you should try to reduce allocations and release resources


Relasae memory on onstop()



When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.

Friday 2 December 2016

OutofMemory Info

Out of memory error is very common error when you are developing for a application that deals with multiple images sets or large bitmaps or some Animation stuff. In this case we have to be very careful and efficient while handling the images or object allocation and deallocation. OOM error comes when the allocation crosses the heap limit or your process demand a amount of memory that crosses the heap limit.
In Android, every application runs in a Linux Process. Each Linux Process has a Virtual Machine (Dalvik Virtual Machine) running inside it. There is a limit on the memory a process can demand and it is different for different devices and also differs for phones and tablets. When some process demands a higher memory than its limit it causes a error i.e Out of memory error.

Possible Reasons:

There are number of reasons why we get a Out of memory errors. Some of those are:
1. You are doing some operation that continuously demands a lot of memory and at some point it goes beyond the max heap memory limit of a process.
2. You are leaking some memory i.e you didn’t make the previous objects you allocated eligible for Garbage Collection (GC). This is called Memory leak.
3. You are dealing with large bitmaps and loading all of them at run time. You have to deal very carefully with large bitmaps by loading the size that you need not the whole bitmap at once and then do scaling.
http://blogs.innovationm.com/android-out-of-memory-error-causes-solution-and-best-practices/



Yes, you can get memory info programmatically and decide whether to do memory intensive work.
Get VM Heap Size by calling:
Runtime.getRuntime().totalMemory();
Get Allocated VM Memory by calling:
Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
Get VM Heap Size Limit by calling:
Runtime.getRuntime().maxMemory()
Get Native Allocated Memory by calling:
Debug.getNativeHeapAllocatedSize();
I made an app to figure out the OutOfMemoryError behavior and monitor memory usage.
You can get the source code at https://github.com/coocood/oom-research

Monday 28 November 2016

How to Store Application Data Locally

https://code.tutsplus.com/tutorials/android-from-scratch-how-to-store-application-data-locally--cms-26853

Background process

Aside from the most basic of Android applications, everything you build will require at least some use of background threading to perform an operation. This is because Android has something known as an ANR(Application Not Responsive) timeout, which is caused when an operation takes five seconds or longer on the UI thread, preventing user input and causing what appears to the user to be a hanging app. 
In order to avoid this, you must move longer running operations, such as network requests or slow database queries, to a different thread so as to not prevent the user from continuing to use your app. Although comprehensive coverage of threading is a large and complex subject in computer science, this tutorial will introduce you to the core concepts of threading in Android, and to some of the tools available to help you build apps that perform better by using background processes.
Generally, the system displays an ANR if an application cannot respond to user input. For example, if an application blocks on some I/O operation (frequently a network access) on the UI thread so the system can't process incoming user input events. Or perhaps the app spends too much time building an elaborate in-memory structure or computing the next move in a game on the UI thread. It's always important to make sure these computations are efficient, but even the most efficient code still takes time to run.
When an application is launched, a new Linux process with a single main execution thread is started. This is the thread that has access to the Android UI toolkit, listens for user inputs, and handles drawing to the Android device screen. Because of this, it is also commonly referred to as the UI thread
All components of an application run within the same thread and process by default, though additional threads can be created to move tasks off the UI thread and prevent an ANR. When it comes to threading in Android, there are two simple rules to remember to keep your app functioning as expected:
  1. Do not block the UI thread.
  2. Do not attempt to access Android UI components from outside the UI thread.
Reference

https://code.tutsplus.com/tutorials/android-from-scratch-background-operations--cms-26810 

Friday 25 November 2016

Broadcast Reciever

Most of us are all too familiar with announcements in public places. They are loud messages that are meant to inform large groups of people about something important. Android applications also have to deal with announcements sometimes—announcements generated either by other applications or by the Android operating system itself. Such announcements are called broadcasts, and they are seen as an important form of asynchronous inter-process communication on the Android platform.



<receiver android:name="MyReceiver">
   
      <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED">
         </action>
      </intent-filter>
   
   </receiver>

https://code.tutsplus.com/tutorials/android-from-scratch-understanding-android-broadcasts--cms-27026

Monday 21 November 2016

Singleton

The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets.
For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.

Implementing Singletons

Example 1

The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance −

// File Name: Singleton.java
public class Singleton {

   private static Singleton singleton = new Singleton();

   /* A private Constructor prevents any other
    * class from instantiating.
    */
   private Singleton() { }

   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }

   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton");
   }
}
// File Name: SingletonDemo.java
public class SingletonDemo {

   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}

Sunday 20 November 2016

Inter process communication



down voteaccepted
There are three types of IPC mechanism in Android:
  1. Intents (along with Bundles)
  2. Binders
  3. ASHMEM (Anonymous Shared Memory) - The main difference between Linux shared memory and this shared memory is, in Linux other processes can't free the shared memory but here if other processes require memory this memory can be freed by Android OS.

Wednesday 16 November 2016

Android screen orientation Lifecycle

Android screen orientation Lifecycle

We might have some confusion on the android screen orientation change lifecycle of an Android activity.  Sometimes you might observe  that your activity getting restarted, while the you rotate the device. Sometimes nothing happens. Below is the simple rule for android screen orientation change lifecycle.
1. If you already @Override the onConfigurationChanged() function in your java code( in your Android activity class) for handle Android Screen Orientation Change. Then your activity will never restart for any screen orientation changes. As i explained it in point-4 above.
2. If you do not @Override onConfigurationChanged() function as above, then your running activity will get restart every time for any screen orientation change happens in your device. That means your activity will destroy first by calling onDestroy() API and then onCreate()method will call again for your running activity to restart it.
3. To properly handle your activity’s restart state, you need to restores its previous state through the normal Activity lifecycle, in which Android OS calls onSaveInstanceState() method before it destroys your activity. So that you can save your data(variable values)and your application state. You can then restore the previous state during onCreate() or onRestoreInstanceState() method call of your activity.

Service

Android user interface is restricted to perform long running jobs to make user experience smoother.
 A typical long running tasks can be periodic downloading of data from internet, saving multiple records into database, perform file I/O, fetching your phone contacts list, etc. For such long running tasks, Service is the alternative.

  1. A service is a application component used to perform long running tasks in background.
  2. A service doesn’t have any user interface and neither can directly communicate to an activity.
  3. A service can run in the background indefinitely, even if component that started the service is destroyed.
  4. Usually a service always performs a single operation and stops itself once intended task is complete.
  5. A service runs in the main thread of the application instance. It doesn’t create its own thread. If your service is going to do any long running blocking operation, it might cause Application Not Responding (ANR).  And hence, you should create a new thread within the service.

service is a component that is used to perform operations on the background such as playing music, handle network transactions, interacting content providers etc. It doesn't has any UI (user interface).
The service runs in the background indefinitely even if application is destroyed.
Moreover, service can be bounded by a component to perform interactivity and inter process communication (IPC).
The android.app.Service is subclass of ContextWrapper class.

Different Type of Service:-

  • Unbound Service
  • It is a kind of service which runs in the background indefinitely, even if the activity which started this service ends.
  • Bound Service
  • It is a kind of service which runs till the lifespan of the activity which started this service

Life Cycle of Android Service

There can be two forms of a service.The lifecycle of service can follow two different paths: started or bound.
  1. Started
  2. Bound

1) Started Service

A service is started when component (like activity) calls startService() method, now it runs in the background indefinitely. It is stopped by stopService() method. The service can stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method. The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.






                                          Difference between Service and Intentservice

Service is a base class of service implementation. Service is run in the application's main thread which may reduce the application performance. Thus, IntentService, which is a direct subclass of Service is available to make things easier.
The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminates itself automatically. Examples for its usage would be to download a certain resource from the Internet.
Differences
  1. Service class uses the application's main thread, while IntentService creates a worker thread and uses that thread to run the service.
  2. IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly. Service class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when it finishes execution.
  3. IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.
  4. IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().
In brief, there are only two things to do to use IntentService. Firstly, to implement the constructor. And secondly, to implement onHandleIntent(). For other callback methods, the super is needed to be called so that it can be tracked properly.

Wednesday 2 November 2016

ANDROID IMPORTANT LIBRARY


 Systrace 


The Systrace tool helps analyze the performance of your application by capturing and displaying execution times of your applications processes and other Android system processes. The tool combines data from the Android kernel such as the CPU scheduler, disk activity, and application threads to generate an HTML report that shows an overall picture of an Android device’s system processes for a given period of time.


stetho is a debug bridge for Android applications, enabling the powerful Chrome Developer Tools and much more.

https://github.com/facebook/stetho

MaterialLibrary is an Open Source Android library that back-port Material Design components to pre-Lolipop Android. MaterialLibrary's original author is Rey Pham
http://rey5137.com/material/





This application provides a collection of third party libraries, as a developer this application is essential for you.
You will have information about the author, captures, license, description, links of the library and you can try a working example within the application.
Recently it has added a tab with SNIPPETS that will be updated constantly.

https://play.google.com/store/apps/details?id=com.desarrollodroide.repos

Mobile User Interface design helps users to use and work with application easily. Tabs also come in user interface part and makes easy to explore and switch between different views. UI design apps are user friendly and also it helps to increase rating of your application and game. In this post, I have collected some beautiful and amazing tabs ui design for you mobile apps.

http://www.viralandroid.com/2015/09/beautiful-mobile-tabs-ui-design-with-amazing-user-experience.html


Android Library to make a cool intro for your app.

github----https://github.com/PaoloRotolo/AppIntro
https://play.google.com/store/apps/details?id=paolorotolo.github.com.appintroexample


android smart animation

https://github.com/ratty3697/android-smart-animation-library

Difference type of theme for android app

https://play.google.com/store/apps/details?id=com.hexagon.design.ws.hexagon
https://play.google.com/store/apps/details?id=com.wolfsoft.fivedemo

https://play.google.com/store/apps/details?id=com.csform.android.uiapptemplate
https://play.google.com/store/apps/details?id=com.ionicframework.ionictemplates735700



Card Example

Cards Library provides an easy way to display a UI Card in your Android app.
You can display single cards, list of cards and a grid of Cards.
You can find the project on Github (https://github.com/gabrielemariotti/cardslib)


For All of camera 

https://play.google.com/store/apps/details?id=com.jnardari.opencv_androidsamples

Tab with slide animation
https://github.com/Gilgoldzweig/EasyTabs

Using Fan Layout Manager you can implement the horizontal list, the items of which move like fan blades (in a circular way of a radius to your choice). To give a slightly chaotical effect to the motion, it’s possible to set an angle for the list items. So, every implementation of the library can be unique.

https://github.com/Cleveroad/FanLayoutManager

Mobile User Interface design helps users to use and work with application easily. Tabs also come in user interface part and makes easy to explore and switch between different views. UI design apps are user friendly and also it helps to increase rating of your application and game. In this post, I have collected some beautiful and amazing tabs ui design for you mobile apps.

http://www.viralandroid.com/2015/09/beautiful-mobile-tabs-ui-design-with-amazing-user-experience.html


This library provides a simple way to add a draggable sliding up panel (popularized by Google Music and Google Maps) to your Android application.

A beautiful, fluid, and customizable dialogs API. 
https://github.com/umano/AndroidSlidingUpPanel


Simple, pretty and powerful logger for android
Logger provides :
  • Thread information
  • Class information
  • Method information
  • Pretty-print for json content
  • Pretty-print for new line "\n"
  • Clean output
  • Jump to source
https://github.com/orhanobut/logger



SnappyDB is a key-value database for Android it's an alternative for SQLite if you want to use a NoSQL approach.
It allows you to store and get primitive types, but also a Serializable object or array in a type-safe way.

SnappyDB can outperform SQLite in read/write operations. 

https://github.com/nhachicha/SnappyDB