Core Java Concepts: Inheritance, Polymorphism
Core Java Concepts: Inheritance, Polymorphism
What is Inheritance?
one class acquires the properties (methods and fields) of another. With the use of
inheritance the information is made manageable in a hierarchical [Link] uses
the keyword e xtends to inherit the properties of a class.
What is Polymorphism?
Polymorphism in Java has two types: Compile time polymorphism (static binding) and
Runtime polymorphism (dynamic binding). Method overloading is an example of static
polymorphism, while method overriding is an example of dynamic polymorphism.
Abstraction?
Abstraction is the concept of hiding the internal details and describing things in simple
terms. For example, a method that adds two integers. The method internal processing is
hidden from outer world. There are many ways to achieve abstraction in object oriented
programming, such as encapsulation and inheritance.A java program is also a great
example of abstraction. Here java takes care of converting simple statements to
machine language and hides the inner implementation details from outer world.
Encapsulation?
overloading :Same method name and parameters are different in same class.
Overloading happens at [Link] type of method does not matter in case of
method overloading, it can be same or different.
Overriding : Same method name and same parameters in parent and child
[Link] happens at runtime. The overriding method can have more specific
return type (meaning if, for example, base method returns an instance of Number class,
all overriding methods can return any class that is extended from Number, but not a
class that is higher in the hierarchy, like, for example, Object is in this particular case).
The s
tatic method in Cat // testClassMethod() is called from "Cat" reference
The s tatic method in Animal // testClassMethod() is called from "Animal" reference,
// ignoring actual object inside it (Cat)
The instance method in Cat // testInstanceMethod() is called from "Animal" reference,
// but from "Cat" object underneath
1. Static binding in Java occurs during compile time while dynamic binding occurs
during runtime.
inal and s
2. private, f tatic methods and variables use static binding and are
bonded by compiler while virtual methods are bonded during runtime based
upon runtime object.
3. Static binding uses T ype (class in Java) information for binding while dynamic
binding uses object to resolve binding.
4. Overloaded methods are bonded using static binding while overridden methods
are bonded using dynamic binding at runtime.
An abstract class, is a class that contains both concrete and abstract methods
(methods without implementations). An abstract method must be implemented by the
abstract class sub-classes. Abstract classes cannot be instantiated and need to be
extended to be used.
Yes, an interface can implement another interface (and more than one), but it needs to
use e xtends, rather than implements keyword. And while you can not remove methods
from parent interface, you can add new ones freely to your subinterface.
What are the access modifiers you know? What does each one do?
There are four access modifiers in Java language (from strictest to the most lenient):
a. private variables, methods, constructors or inner classes are only visible to its'
containing class and its' methods. This modifier is most commonly used, for
example, to allow variable access only through getters and setters or to hide
underlying implementation of classes that should not be used by user and
therefore maintain encapsulation. Singleton constructor is also marked private to
avoid unwanted instantiation from outside.
b. protected can be used on variables, methods and constructors therefore allowing
access only to subclasses and classes that are inside the same package as
protected members' class.
c. Default (no keyword is used) this modifier can be applied to classes, variables,
constructors and methods and allows access from classes and methods inside
the same package.
d. public modifier is widely-used on classes, variables, constructors and methods to
grant access from any class and method anywhere. It should not be used
everywhere as it implies that data marked with p ublic is not sensitive and can not
be used to harm the program.
"Hello, World!" is called a literal and compiler creates a String object with its' value. So
String capital = "Hello, World!".toUpperCase();
is a valid statement, that, firstly, will create an object with literal value "Hello, World!"
and then will create and return another object with value "HELLO, WORLD!"
Objects of String are immutable, and objects of StringBuffer and StringBuilder are
[Link] and StringBuilder are similar, but StringBuilder is faster and
preferred over StringBuffer for single threaded program. If thread safety is needed, then
StringBuffer is used.
StringBuffer
● Mutable - can be modified after creation
● Synchronized - multiple threads can access it and modify it without any side effects
● Relatively slow process. Many locking and unlocking actions will take place
StringBuilder
● Mutable - can be modified after creation
● Not synchronized - accessing it and modifying it by more than one threads can produce
unexpected results!
● Much faster than the StringBuffer class
public class MyObjects implements Parcelable { private int age; private String
name; private ArrayList<String> address; public MyObjects(String name, int age,
ArrayList<String> address) { this.name = name; this.age = age; this.address =
address; } public MyObjects(Parcel source) { age = [Link](); name =
[Link](); address = [Link](); }
@Override
@Override
[Link](name); [Link](address); }
public int getAge() { return age; } public String getName() { return name; }
public ArrayList<String> getAddress() { if (!(address == null)) return address;
else return new ArrayList<String>(); } public static final Creator<MyObjects>
CREATOR = new Creator<MyObjects>() { @Override public MyObjects[] newArray(int
size) { return new MyObjects[size]; } @Override public MyObjects
createFromParcel(Parcel source) { return new MyObjects(source); } }; }
Drawbacks:
● Step 1: private static variable of the INSTANCE of the same class (this is only time
instance of this class get created)
● Step 2: Provide private constructor to restrict instatiation from outside class
● Step 3: Provide public static getInstance() method returning same INSTANCE every time
● Note: These are steps for eager initialization
1
package [Link];
2
3
4
5 public class SingletonDesignPatternWithEagerInitialization {
6
7
8 // Step 1: private static variable of INSTANCE variable
9
10 private static SingletonDesignPatternWithEagerInitialization
11
INSTANCE = new SingletonDesignPatternWithEagerInitialization();
12
13
14
// Step 2: private constructor
15
16 private SingletonDesignPatternWithEagerInitialization() {
17
18
19
}
20
getInstance() {
return INSTANCE;
}
}
Problem :
2. Lazy Instantiation :
We can actually write more improved version of above code with Lazy initialization
● Step 1: Just declare private static variable of the same class (beware don’t instantiate)
● Step 2: Provide private constructor to restrict instatiation from outside class
● Step 3: Provide public static getInstance() method and check
1. Step 3.a: If INSTANCE variable is null, then only instantiate
2. Step 3.b: Otherwise, return already instantiated INSTANCE variable
● Note: These are steps for lazy initialization
24
INSTANCE = new
25
SingletonDesignPatternWithLazyInitialization();
}
return INSTANCE;
}
}
3. Singleton design pattern in a multi-threaded environment
Problems of Lazy-Initialization :
● Although, we have done performance optimization for singleton design pattern with lazy
initialization but still there are certain problems
● So, before we start coding singleton class in a multi-threaded environment we should
understand problem with lazy initialization first
● In the above example for Lazy Initialization, suppose 2 or more threads execute in parallel or
concurrent, then there may be a issue with multiple instances being instantiated
To overcome this situation, we need to execute lazy instance creation inside synchronized block
Basic steps to create Singleton class using Lazy Initialization in a Multi-threaded environment
● Step 1: Just declare private static variable of the same class (beware don’t instantiate)
● Step 2: Provide private constructor to restrict instantiation from outside class
● Step 3: Provide public static getInstance() method and check
1. Step 3.a: If INSTANCE variable is null, then only instantiate
2. Step 3.b: Otherwise, return already instantiated INSTANCE variable
3. Synchronized: Put both above checks inside synchronized block
● Step 4: In addition to above detailed steps, also make INSTANCE variable as volatile. This
will help getting latest updated copy every time, as it will read from main memory than in its
own CPU-cache area
● Note: If your singleton INSTANCE is going to be executed in a single threaded environment,
then there is no need of making INSTANCE variable as volatile
[Link]
?
1
package [Link];
2
3
4
5 public class SingletonDesignPatternInMultiThreadedEnvironment {
6
7
8 // Step 1: private static variable of INSTANCE variable
9
10 private static volatile
11
SingletonDesignPatternInMultiThreadedEnvironment INSTANCE;
12
13
14
// Step 2: private constructor
15
16 private SingletonDesignPatternInMultiThreadedEnvironment() {
17
18
19
}
20
21
22
23 // Step 3: Provide public static getInstance() method
24
// returning INSTANCE after checking
25
26 public static SingletonDesignPatternInMultiThreadedEnvironment
27
getInstance() {
28
29
30
// synchronized block
synchronized
([Link]){
if(null == INSTANCE){
INSTANCE =
new
SingletonDesignPatternInMultiThreadedEnvironment();
}
return INSTANCE;
}
}
}
This way, we can assure that every time single & same instance is returned
But again, there is a performance issue with above program. Let us understand,
● Assume that ONE instance is created and available for use (i.e.; singleton instance)
● And with this single & same instance, some thread (Thread-Arya) is executing in a
multi-threaded environment
● Now suppose a new thread (Thread-Surya) got execution cycle and trying to get singleton
instance, although it is already created & available for use
● But Thread-Surya has to wait till Thread-Arya releases lock or comes out of synchronized
block
● This is bad and poor situation, reason being singleton instance is already created and still it
has to wait to get that instance
● Ideally speaking, Thread-Surya doesn’t need to wait for Thread-Arya to release lock and
then check condition and then proceed with its execution
To design such pattern, we need to look into double-checked locking design pattern
[Link]
?
1
public class SingletonDesignPatternWithDCL {
2
3 // Step 1: private static variable of INSTANCE variable
4
5 private static volatile SingletonDesignPatternWithDCL
6
INSTANCE;
7
8 // Step 2: private constructor
9
10 private SingletonDesignPatternWithDCL() {
11
}
12
13 // Step 3: Provide public static getInstance() method
14
// returning INSTANCE after checking
15
16 public static SingletonDesignPatternWithDCL getInstance() {
17
18 // double-checking lock
19
if(null == INSTANCE){
20
21 // synchronized block
22
23 synchronized ([Link]) {
24
if(null == INSTANCE){
25
26 INSTANCE = new SingletonDesignPatternWithDCL();
27
}
28
29 }
30
}
return INSTANCE;
}
}
Conclusion:
We have covered almost for every possible situation that may arise problem while dealing with
Singleton design pattern; like
● Eager initialization
● Lazy initialization
● Lazy initializtion in a multi-threaded environment
● Double checking lock desing pattern
It is a design choice to choose from above listed approaches to begin with, as starting with
double-checking lock in a non-threaded environment yields poor results
So, it is always design choice to look that which approach fits our case perfectly for our business
requirement
There are mainly 3 concepts which can break singleton property of a class.
Reflection, Serialization,Cloning.
Reflection
import [Link];
Singleton instance1 = [Link];
Singleton instance2 = null;
try
{
Constructor[] constructors =
[Link]();
for (Constructor constructor : constructors)
{
// Below code will destroy the singleton pattern
[Link](true);
instance2 = (Singleton)
[Link]();
break;
}
}
catch (Exception e)
{
[Link]();
}
Overcome reflection issue: To overcome issue raised by reflection, enums are used
because java ensures internally that enum value is instantiated only once. Since java
Enums are globally accessible, they can be used for singletons. Its only drawback is that
catch (Exception e)
{
[Link]();
}
Overcome serialization issue:- To overcome this issue, we have to implement method
readResolve() method
// implement readResolve method
protected Object readResolve()
{
return INSTANCE;
}
Cloning: C
loning is a concept to create duplicate objects. Using clone we can create
copy of object. Suppose, we create clone of a singleton object, then it will create a copy
that is there are two instances of a singleton class, hence the class is no more
singleton.
// JAVA code to explain cloning
// issue with singleton
class SuperClass implements Cloneable
{
int i = 10;
@Override
protected Object clone() throws CloneNotSupportedException
{
return [Link]();
}
}
// Singleton class
class Singleton extends SuperClass
{
- - ------
- }
Singleton instance1 = [Link];
Singleton instance2 = (Singleton) [Link]();
Overcome Cloning issue:- To overcome this issue, override clone() method and throw
an exception from clone method that is CloneNotSupportedException. Now whenever
user will try to create clone of singleton object, it will throw exception and hence our
class remains singleton.
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
Hashtable and HashMap
Hashtable was part of the original [Link] and is a concrete implementation of a
Dictionary.
However, Java 2 re-engineered Hashtable so that it also implements the Map interface.
Thus, Hashtable is now integrated into the collections framework. It is similar to
HashMap, but is synchronized.
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a
Hashtable, you specify an object that is used as a key, and the value that you want
linked to that key. The key is then hashed, and the resulting hash code is used as the
index at which the value is stored within the table.
Set is a collection that contains no duplicate elements. Set is an interface.. A TreeSet is a
set where the elements are sorted (and thus ordered), a HashSet is a set where the
elements are not sorted or ordered. A HashSet is typically a lot faster than a TreeSet.
Sorting in Java
A comparable object is capable of comparing itself with another object. The class itself
sort a list of Movies based on year of release. We can implement the Comparable
interface with the Movie class, and we override the method compareTo() of Comparable
interface.
import [Link].*;
import [Link].*;
// Constructor
[Link] = nm;
[Link] = rt;
[Link] = yr;
[Link](list);
Collections class has a second sort() method and it takes Comparator. The sort()
method invokes the compare() to sort objects.
// Class to compare Movies by ratings
class RatingCompare implements Comparator<Movie>
{
public int compare(Movie m1, Movie m2)
{
if ([Link]() < [Link]()) return -1;
if ([Link]() > [Link]()) return 1;
else return 0;
}
}
compareTo() (from interface Comparable) returns an integer. It checks which of the two
objects is "less than", "equal to" or "greater than" the other. Not all objects can be logically
ordered, so a compareTo() method doesn't always make sense.
ProGuard
ProGuard is the technique to shrink the code, which detects and remove the unused
classes, fields, methods, packages and attributes (including code libraries).
Obfusator: It renames the optimize classes, methods with short names. (Used to
prevent Reverse Engineering).
Preverifier: It converts the optimize code into optimize jars and libs.
First generate the apk with the applied proguard build type, you
may get some errors and warning on apk generation (These are
normal we are facing also)
-If you getting errors like ClassNotFoundExceptions or may crash
the app then you have to keep those classes which are not found
or causes errors.
like this for classes, also can apply for members and fields
-dontwarn <classes_name>
-dontwarn retrofit2.**
-dontwarn [Link].*
-dontwarn okio.**
Stack: Stack is a linear data structure which follows a particular order in which the
operations are performed. The order is LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
● Push: Adds an item in the stack. If the stack is full, then it is said to be an
Overflow condition.
● Pop: Removes an item from the stack. The items are popped in the reversed
order in which they are pushed. If the stack is empty, then it is said to be an
Underflow condition.
● Peek or Top: Returns top element of stack.
● isEmpty: Returns true if stack is empty, else false.
public IntStack(){
top = -1;
size = 100;
stack = new int[size];
}
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow
condition.
Dequeue: Removes an item from the queue. The items are popped in the same order in
which they are pushed. If the queue is empty, then it is said to be an Underflow
condition.
public IntQueue() {
front = 0;
rear = 0;
total = 0;
size = 100;
q = new int[size];
front = 0;
rear = 0;
total = 0;
[Link] = size;
q = new int[[Link]];
if (total == [Link]) {
return true;
} else {
return false;
if(total == 0){
return true;
} else {
return false;
[Link]("Queue is full");
return false;
}else{
q[rear] = item;
return true;
if(isEmpty()){
[Link]("Queue is empty");
return Integer.MIN_VALUE;
}else{
total = total - 1;
return value;
}
public void showAll(){
int f = front;
f = (f+1)%size;
return total;
if(isEmpty()){
[Link]("Queue is empty");
return Integer.MIN_VALUE;
}else{
return q[front];
[Link]("Queue is empty");
return Integer.MIN_VALUE;
}else{
return q[rear];
Linked List: A
linked list is a linear data structure, in which the elements are not stored
at contiguous memory locations. In simple words, a linked list consists of nodes where
each node contains a data field and a reference(link) to the next node in the list. The
elements in a linked list are linked using pointers as shown in the below image:
If the given array has to be sorted in ascending order, then bubble sort will start by
comparing the first element of the array with the second element, if the first element is
greater than the second element, it will swap both the elements, and then move on to
compare the second and the third element, and so on.
If we have total n elements, then we need to repeat this process for n-1 times.
It is known as bubble sort, because with every complete iteration the largest element in the
given array, bubbles up towards the last place or the highest index.
Int n = arr.length;
bubbleSort(arr, n);
lag = 0;
f
emp = arr[j];
t
arr[j] = arr[j+1];
arr[j+1] = temp;
lag = 1;
f
// if value of flag is zero after all the iterations of inner loop
break;
}
Android
A new instance of actvity is created everytime in the task from which it was started.
Multiple instances of activity can be created and each instance may belong to different
task.
SingleTop
If instance of activity is present on top of Task stack, a new instance will not be created
and system will route your intent information through onNewIntent(). If it is not presnt on
top, a new instance will be created. Multiple instance can be created and each instance
may belong to different task.
SingleTask
A new task will be created and a new instance of the activity will be pushed at root of
new task. If instance exists on the seperate task then system routes the call to existing
instance through onNewIntent() method. Only one instance will exist at a time.
SingleInstance
● Database: Contains the database holder and serves as the main access point for
the underlying connection to your app's persisted, relational data.
● The class that's annotated with @
Database should satisfy the following
conditions:
○ Be an abstract class that extends RoomDatabase.
○ Include the list of entities associated with the database within the
annotation.
○ Contain an abstract method that has 0 arguments and returns the class
that is annotated with @Dao.
● At runtime, you can acquire an instance of D
atabase by calling
[Link]() or[Link]().
Room.databaseBuilder(context, AppDatabase.class,
dbName).fallbackToDestructiveMigration().build();
@Entity(tableName = "videos",
indices = {@Index("title")})
@Dao
public interface VideoDao {
// Create insert with custom conflict strategy
@Insert(onConflict = [Link])
void saveVideos(List<VideoItem> videos);
}
Use in Application class or provide via Dagger
ContentDatabase provideContentDatabase() {
return [Link](context, [Link], "[Link]")
.addMigrations([Link]).build();
}
RxAndroid is specific to Android platform which utilises some classes on top of the
RxJava library.
RxJava is all about two key components: Observable and Observer. In addition to
these, there are other things like Schedulers, Operators and Subscription.
Observable: Observable is a data stream that do some work and emits data.
Observer: Observer is the counter part of Observable. It receives the data emitted by
Observable.
Schedulers: Schedulers decides the thread on which Observable should emit the data
and on which Observer should receives the data i.e background thread, main thread
etc.,
● Observable
● Flowable
● Single
● Maybe
● Completable
● Observer
● SingleObserver
● MaybeObserver
● CompletableObserver
#Annotations
Annotations are the class of metadata, that can be associated with class, methods, fields
and even other annotations. Annotations in Java are used to provide additional
information, so it is an alternative option for XML and Java marker interfaces. These
methods can also be accessed during the runtime via reflections.
#Annotation Processors
Annotation processors are the code generators that eliminate the boilerplate code, by
creating code for you during the compile time. Since it’s compile time, there is no
overhead in the performance.
You can set static headers for a method using the @Headers annotation.
@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
@Headers({
"Accept: application/[Link]+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
Note that headers do not overwrite each other. All headers with the same name will be
corresponding parameter must be provided to the @Header. If the value is null, the header will
be omitted. Otherwise, t oString will be called on the value, and the result used.
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
Similar to query parameters, for complex header combinations, a Map can be used.
@GET("user")
anOkHttpinterceptor.
Simply we can say FCM (Firebase Cloud Messaging) is a new version of GCM
(Google Cloud Messaging). It is a cross-platform messaging solution that lets you
reliably deliver messages at no cost. Using FCM, you can send notification messages to
drive user re-engagement and retention.
[Link]
ging-c37d165b8320
Fabric(Custom)
[Link]
Service vs IntentService
When to use?
● The Service can be used in tasks with no UI, but shouldn't be too long. If you
need to perform long tasks, you must use threads within Service.
● The IntentService can be used in long tasks usually with no communication to
Main Thread. If communication is required, can use Main Thread handler or
broadcast intents. Another case of use is when callbacks are needed (Intent
triggered tasks).
How to trigger?
Triggered From
● The Service and IntentService may be triggered from any thread, activity or
other application component.
Runs On
● The Service runs in background but it runs on the Main Thread of the
application.
● The IntentService runs on a separate worker thread.
Limitations / Drawbacks
When to stop?
● If you implement a Service, it is your responsibility to stop the service when its
work is done, by calling stopSelf() or stopService(). (If you only want to
provide binding, you don't need to implement this method).
● The IntentService stops the service after all start requests have been handled,
so you never have to call s topSelf().
1. START_STICKY – When you set your service is started sticky it means it will restart
your service again by Android when memory is available to execute the task. But before
make sure that you do not pass any intent data because intent data will be lost when
service is killed. So we will receive null intent data on startCommand().
2. START_NOT_STICKY – When you set the flag to start not sticky then it will not start
your service if it killed by android resource and some more flag are available you can
check on the official developer site. You can set your flag as below.
1 @Override
5 return START_STICKY; // you can set the flag as per your requirement.
6
7 }
Bound service
Bound service is one that allows binding service with the client. This service will
continue running the client unbind it. This service will start running when it binds to
bindService(). This kind of service provides the option to the client with either in the
same process or different process. For the different process, it binds remotely by IPC
(inter-process communication).
Let’s first check How it works bind service in the application. Service can bind either by
activity or broadcast. What you need to do just call bindService(). For binding the
service You need to pass the IBinder instance in onBind() life cycle of service.
Whenever your task has completed then unBind() service from the client. Here is an
example to understand the concept.
1 public class MyService extends Service{
5 @Nullable
6 @Override
8 return mBinder;
9 }
10
12
13 MyService getService(){
14 return [Link];
15 }
16 }
17
20 }
21
24 }
25 }
Let’s create an activity to bind this service and access this method inside the client.
1 public class BindServiceActivity extends AppCompatActivity {
3 MyService myService;
6 @Override
8 [Link](savedInstanceState);
9 setContentView([Link].activity_bind_service);
1
0
((Button) findViewById([Link].btn_start)).setOnClickListener(new
1 [Link]() {
1
@Override
1
2 public void onClick(View v) {
1 getServiceMessage();
3
}
1
});
4
}
1
5
1
6
private void getServiceMessage() {
1
7 // call the localService methods Here
2
1 // Here need to create the service connection
2 myService = [Link]();
6
isBind = true;
2
7
2
8 }
2
9
@Override
3
0 public void onServiceDisconnected(ComponentName name) {
3 isBind = false;
1
}
3
};
2
3
3
3 @Override
4
protected void onSart() {
3
5 [Link]();
3
8 @Override
3 protected void onStop() {
9
[Link]();
4
0 if (isBind) {
unbindService(serviceConnection);
4 }
1
}
4
2 }
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
Messenger
Messenger will process the message in a different process by using IPC (Inter Process
Communication) remote technique to communicate with client and server. Messenger
will be coupled with the handler, hence all the task will be in queue process in a Single
thread by Handler.
For bind the service what you need to do with pass the Messenger instance reference in
onBind() method and pass the reference of handler while creating the Messenger
instance. Hereabouts message will be carried in the format of the bundle with
Messenger that it awesome. Let’s see for example to create one service which runs in
the different process by using Messenger which is the coupled by Handler.
1 public class MyServiceIPC extends Service {
8 @Nullable
9 @Override
11 return [Link]();
12 }
13
15 @Override
17
18 Message message;
20 String messageText;
21
22 switch ([Link]) {
23 case JOB_1:
24 messageText = [Link]().getString("message");
26 [Link](getApplicationContext(),messageText ,
Toast.LENGTH_SHORT).show();
27
[Link]("message_res", [Link]());
28
[Link](bundle);
29
Messenger activityMessenger = [Link];
30 try {
31 [Link](message);
32 } catch (RemoteException e) {
33 [Link]();
34 }
35 break;
36 default:
37 [Link](msg);
38 }
39
40 }
41 }
42 }
Now let’s create activity class to bind this service to send the message to this server
and again send back this response from server to client by using Messenger process by
the handler.
1 public class BindServiceIPCActivity extends AppCompatActivity {
8 new ResponseTakeHandler(this));
1
0
@Override
1
1 protected void onCreate(@Nullable Bundle savedInstanceState) {
1 [Link](savedInstanceState);
2
setContentView([Link].activity_bind_ipc);
1
3
editText = (EditText)findViewById([Link]);
1
4 btnSend = (Button)findViewById([Link]);
1 [Link](new [Link]() {
5
@Override
1
6 public void onClick(View v) {
1
7
String messageText = [Link]().toString();
1
if ([Link]()){
8
[Link]([Link], "Please enter
1
message", Toast.LENGTH_LONG).show();
9
}else{
2
0 Message message = [Link](null,MyServiceIPC.JOB_1);
2 } catch (RemoteException e) {
5
[Link]();
2
}
6
}
2
7
2 }
8
});
2
9
3 }
0
3
@Override
1
protected void onStart() {
3
2 [Link]();
3 if (!isBound) {
3
// start service here
3
4 Intent intent = new Intent([Link],
[Link]);
3
5 bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
3 }
6
}
3
7
3 @Override
8 protected void onStop() {
3 [Link]();
9
isBound = false;
4
0 messenger = null;
}
4
1
ServiceConnection serviceConnection = new ServiceConnection() {
4
2 @Override
4 @Override
6
public void onServiceDisconnected(ComponentName name) {
4
7 isBound = false;
4 messenger = null;
8
4
}
9
};
5
0
5
1
public class ResponseTakeHandler extends Handler{
5
2
5
4 }
5 @Override
5 public void handleMessage(Message msg) {
5
6
switch ([Link]){
5
7 case MyServiceIPC.JOB_RESPONSE_1:
6 }
1
6
}
2
}
6
3
6 }
4
6
5
6
6
6
7
6
8
6
9
7
0
7
1
7
2
7
3
7
4
7
5
7
6
7
7
7
8
7
9
8
0
8
1
8
2
8
3
8
4
8
5
8
6
8
7
8
8
8
9
9
0
9
1
9
2
9
3
9
4
9
5
9
6
Here also required the Service Connection to build the connection between the client
and the server. The handler will process the response of Messenger and update the
user interface. But one more thing does not forget to add this service in
[Link].
AIDL
AIDL means android interface definition [Link] can process any task remotely by
using IPC technique. Android has a strong mechanism to communicate between service
and client through IPC technique. AIDL process the data between clients remotely and
safely only thing is required that client should be bind to this services. AIDL support to
process the generic data by using the Parcelable. Data processing through Parcelable
is fast in IPC mechanism. Different process means I am talking about the
communication between two different applications.
I think it’s big complex example, Let’s give another simple example to explain. I want to
multiply by given two numbers. I will pass two different numbers as input and will tell to
AIDL service to give the result as a response back to me. It is simple task here but it
can take any long background task to the process, for example, downloading any audio
or video files from the server.
For communication with two different apps or process, I need to create the AIDL file in
the same package of both apps. Why AIDL is required on client side also it will create
the copy of proxy for remote access.
Let’s create two different android studio project for App1 and App2.
1 // [Link]
2 package [Link];
6 interface MultiplyNumberAidl {
7
9 }
3 @Nullable
4 @Override
7 @Override
You need to set the build and sync to access the aidl file.
1 sourceSets {
2 main {
3 [Link] = ['src/main/aidl']
4 }
5 }
</service>
Now in App2, I will try to access the service to get the result. You need to bind via
explicit intent service with the client by ServiceConnection.
public class MultiplyNumberAidlActivity extends
AppCompatActivity {
@BindView([Link].editText_First)
EditText firstNumEditText;
@BindView([Link].editText_Second)
EditText secondNumEditText;
@BindView([Link])
Button btnAdd;
MultiplyNumberAidl aidlService;
@Override
setContentView([Link].activity_aidl);
[Link](this);
initView();
[Link](new [Link]() {
@Override
String firstNumber =
[Link]().toString().trim();
String secondNumber =
[Link]().toString().trim();
}else{
try {
multiply =
[Link]([Link](firstNumber),
[Link](secondNumber));
} catch (RemoteException e) {
[Link]();
[Link]([Link], ""+multiply,
Toast.LENGTH_SHORT).show();
});
}
@Override
[Link]();
Intent updateIntent =
createExplicitFromImplicitIntent([Link]
, intent);
bindService(updateIntent, serviceConnection,
Context.BIND_AUTO_CREATE);
return null;
//Create a new intent. Use the old one for extras and such
reuse
Intent explicitIntent = new Intent(implicitIntent);
[Link](component);
return explicitIntent;
@Override
aidlService =
[Link](service);
@Override
public void onServiceDisconnected(ComponentName name) {
aidlService = null;
};
An intent filter is an expression in an app's manifest file that specifies the type of
intents that the component would like to receive.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = [Link](
this, [Link].activity_sample);
[Link]([Link]);
}
● Use LiveData to build data objects that notify views when the underlying
database changes.
● ViewModel Stores UI-related data that isn't destroyed on app rotations.
● Room is an a SQLite object mapping library. Use it to Avoid boilerplate code and
easily convert SQLite table data to Java objects. Room provides compile time
checks of SQLite statements and can return RxJava, Flowable and LiveData
observables.
LiveData: LiveData is an observable data holder. When ever the data is
changed(DB/Network) its automatically updated in the [Link] is
lifecycle-aware, meaning it respects the lifecycle of other app components, such
as activities, fragments, or services. This awareness ensures LiveData only
updates app component observers that are in an active lifecycle state.
LiveData has no publicly available methods to update the stored data. The
MutableLiveData class exposes the setValue(T) and postValue(T) methods
publicly and you must use these if you need to edit the value stored in a LiveData
object. Usually MutableLiveData is used in the ViewModel and then the
ViewModel only exposes immutable LiveData objects to the observers.
ViewModel: is a class that is responsible for preparing and managing the data
for an Activity or a Fragment.ViewModel Stores UI-related data that isn't
destroyed on app [Link] will not be destroyed if its owner is
destroyed for a configuration change (e.g. rotation). The new instance of the
owner will just re-connected to the existing ViewModel.
MVVM: it allows separating the user interface logic from the business (or the
back-end) [Link] UI code simple and free of app logic in order to make it
easier to manage
Model - Model represents the data and business logic of the [Link] is to expose
its data through observables
ViewModel - ViewModel interacts with model and also prepares observable(s)
that can be observed by a View. ViewModel should not be aware about the view
who is interacting with.
View - Finally, the view role in this pattern is to observe (or subscribe to) a
ViewModel observable to get data in order to update UI elements accordingly.
apply() or commit()
The [Link]() method is asynchronous, while [Link]() is
synchronous.
Obviously, you should call either apply() or commit().
apply() was added in 2.3 (API 9), it commits without returning a boolean indicating
success or failure.
commit() returns true if the save works, false otherwise.
Unlike commit(), which writes its preferences out to persistent storage synchronously,
apply() commits its changes to the in-memory S haredPreferences immediately but
starts an asynchronous commit to disk and you won't be notified of any failures. If
another editor on this S haredPreferences does a regular c ommit() while a a
pply() is
ommit() will block until all async commits(apply) are completed as
still outstanding, the c
well as any other sync commits that may be pending.
Exception Handling
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
*/
/**
* Simple string for category log
*/
/**
*/
if (!(Thread.getDefaultUncaughtExceptionHandler()
instanceof ApplicationCrashHandler)) {
Thread.setDefaultUncaughtExceptionHandler(new
ApplicationCrashHandler());
}
private ApplicationCrashHandler() {
[Link] =
Thread.getDefaultUncaughtExceptionHandler();
/**
*/
Override
@
TAG, String.format(
Log.wtf( "Exception: %s\n%s",
[Link](), getStackTrace(e)));
// Call the default handler
[Link](t, e);
/**
* @return t
he stack trace
*/
[Link](pw);
return stacktrace;
@Override
[Link](savedInstanceState);
;
setContentView([Link].activity_splash)
ApplicationCrashHandler.installHandler();
startActivity(intent);
finish();
}
Android Ore Features
1. Picture in Picture
2. Password Auto Fill
3. Notification Channel
4. Snoozed Notifications
5. Notification Dots
6. New Emoji Styling
7. Smart Text selection
8. Auto Enable wifi
SQLite
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//database values
private static final String DATABASE_NAME =
"[Link]";
private static final int DATABASE_VERSION = 3 ;
public static final String COLUMN_ID = " _id";
//team table
public static final String TABLE_TEAM = "team";
public static final String COLUMN_MASCOT = "mascot";
public static final String COLUMN_CITY = "city";
public static final String COLUMN_COACH = "coach";
public static final String COLUMN_STADIUM = "stadium";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_TEAM);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
if (oldVersion < 2) {
db.execSQL(DATABASE_ALTER_TEAM_1);
}
if (oldVersion < 3) {
db.execSQL(DATABASE_ALTER_TEAM_2);
}
}
}
In your Activity:
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
[Link](Calendar.DAY_OF_MONTH,1);
[Link](AlarmManager.RTC_WAKEUP, [Link](),
1000*60*60*24 , pendingIntent);
This will trigger Alarm each day at midnight (12 am). You can change that if you want.
Now, create a Service NotifyService and put this code in its onCreate():
NotificationManager mNM =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
[Link](NOTIFICATION, notification); }
And this code will show the notification when the Alarm is received.
Good Luck!