Thursday, November 15, 2018

How to convert java code into kotlin in android

Kotlin is a language which is supported by Google as a official language for android development.So,
Android Studio 3.0 is now fully supported Kotlin (no need for extra plugin). If you are using Android Studio >= 3.0 then below jobs are very easy :-

1. Converting Existing Java Code into Kotlin :-
Android Studio Menu -> Code -> Convert Java File to Kotlin File
                                                        Or
Create a new Kotlin file and paste your java code in that file- when Android studio prompted for converting java code into kotlin click Yes.

2. Create a new Kotlin file :-
File -> New-> Kotlin File

3. Convert a part of Java code into Kotlin :-
 Copy you java code snippet from Java file and paste into Kotlin file- when Android studio prompted for converting java code into Kotlin click Yes.


Note :- 
1.When you are creating your project in Android studio you have to click include Kotlin support.
2. For older version of Android studio you need to add Kotlin plugin.

Wednesday, November 14, 2018

How to access Telephony class for disconnecting the call without using AIDL in android

Facing problem in adding AIDL classes in android? 
It's not necessary to add ITelephony.aidl class in android, it's convenience to add them. 
So the question is how to use AIDL class in android project?
 The answer is Java Reflection.If you know what is there and what it does, you can use reflection for get them even they are hidden.
For example:- Suppose you want to create a program in which you need to disconnect the call using ITelephony class then there is a method endCall() in that class. Below are code snippet how to use AIDL class using java reflection :-

Java :-

TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
Object telephonyService = m.invoke(tm); // Get the internal ITelephony object
c = Class.forName(telephonyService.getClass().getName()); // Get its class
m = c.getDeclaredMethod("endCall"); // Get the "endCall()" method
m.setAccessible(true); // Make it accessible
m.invoke(telephonyService); // invoke endCall()


Kotlin :-
 
val telephonyService: Any
val telephony =  context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
try{
var c = Class.forName(telephony.javaClass.name)
var m = c.getDeclaredMethod("getITelephony")
m.isAccessible = true
telephonyService = m.invoke(telephony) as Any
c = Class.forName(telephonyService.javaClass.name) // Gets its class
m = c.getDelaredMethod("endCall") // Get the "endCall()' method
m.isAccessible = true //Make it accessible
m.invoke(telephonyService) //invoke endCall()
} catch (e: Exception){
e.printStackTrace()
}
}