Created
January 7, 2019 08:37
-
-
Save ratnapriya4g/38262e0dc897890470ef866b2acb3cda to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Android with Kotlin & Flutter : | |
Android : Android is a Platform consists | |
-> Operating System | |
-> Middleware | |
-> Key Applications | |
Android Components : | |
Core Android : [ 30 sessions ] | |
- Activity | |
- Service | |
- Broadcast Receiver | |
- Content Provider | |
Activity : | |
A single screen in the application with UI components is called as Activity, for every Activity we have to create 2 files( Kotlin , XML file). | |
Service : | |
A long running background process with out any user interaction is called as Service. | |
Broadcast Receiver : | |
Broadcast Receivers are registered for System events. | |
( eg : head set plugin, power connected/disconneted, screen on/off, batter low/full, making/receiving call/sms….) | |
Content Provider : | |
Content Provider is used to share the data between multiple applications. [ In Android it not possible to access the other applications data into our application directly , but if the application is providing content provider then it is possible to access the data. In Android following builtin applications are providing content provider. | |
contacts, call log, settings , messages, calendar, media… ] | |
Advanced Android [ 20 sessions ] : | |
- WebServices [ JSON , GSON , REST API, Retrofit ] | |
- Google API’s | |
- Google Maps - Google Places | |
- Place Picker | |
- Material Design Concepts | |
- Firebase [ Authentication, Database, Storage , | |
Cloud Messaging [ FCM ], Admob ,MLKit,Analatics, | |
Crashlytics ] | |
- Flutter [ Android & iOS ] | |
- MVP [ Model View Presenter ] | |
- Github | |
Kotlin : | |
-> Modern Object Oriented Programming Language. | |
Constructor : | |
- Constructor is a special named block with class name | |
- Constructor invocation is a part object creation. | |
- Constructor is used to initialize the instance variables at the time object creation. | |
- In kotlin there are 2 types of constructor. | |
- Primary Constructor | |
- Secondary Constructor | |
- In a class we can create either primary or secondary constructor. | |
Primary Constructor : | |
syntax : | |
class ClassName( ) // primary constructor with no-args | |
class ClassName(variable_name:DataType) // “ with args | |
class ClassName(var variable_name:DataType) // “ with args | |
- Primary Constructor input parameters can be access only inside init block. | |
init { | |
// code to access constructor input parameters | |
} | |
- In a class we can create only one primary constructor. | |
Secondary Constructor : | |
syntax : constructor( ){ | |
// constructor body | |
} | |
- In a single class we can create multiple secondary constructors. | |
Inheritance : | |
syntax : | |
class ClassNameA : ClassNameB( ) | |
- same like Java Object class, In kotlin every class is a child of Any class. | |
Lamda Expression ‘( )->’ : | |
- an interface with only one abstract function is called as functional interface. | |
- A class with out name is called as Anonymous Inner class. | |
- If Anonymous inner class is providing an implementation for functional interface (or) Anonymous inner class is extending an Abstract class with only one abstarct method that kind of Anonymous inner class we can represent with Lamda Expression ‘( )->’. | |
- If you want to create a child class for an abstract class/ interface instead of creating a separate class we can create Anonymous Inner class. | |
Manifest.xml : | |
- Manifest.xml provides the complete description ( activities, services , permissions, features, icon, launcher screen, etc..) about the application. | |
- Android platform before installing the application and before start the application it reads Manifest.xml. | |
R.java : | |
- R is termed as resource(file). | |
- R.java is an abstraction between resource folder and | |
java/kotlin file. | |
- for every resource in res folder it will generate a static integer field(variable), with the help of static integer filed only we can access the resource in java/kotlin file. | |
APK : | |
- APK is termed as Application Package Kit. | |
- It is a installation file in Android platform. | |
- .apk consists .dex, res , assets , lib and Manifest.xml file. | |
XML : | |
- XML is termed as Extensible Markup Language. | |
- HTML is termed as Hypertext Markup Language. | |
- Enclosing the data with in tags is called as Markup Language. | |
Advantages : | |
- XML is interoperable [ language independent, platform independent] | |
- XML is used to share the data between multiple applications(developed by using same language / different language ). | |
- XML is used as textual database. | |
- XML is used as deployment descriptior. | |
( java -> web.xml, Android - Manifest.xml, iOS - info-plist.xml..) | |
- XML is used for UI designing. | |
Sample XML : | |
<employees> | |
<employee> | |
<id>123</id> | |
<name>Mahesh</name> | |
<desig>TechLead</desig> | |
</employee> | |
</employees> (or) | |
<employees> | |
<employee id=“123” | |
name=“Mahesh” | |
desig=“TechLead”/> | |
</employees> | |
Rules : | |
- every XML element must be properly nested. | |
- every XML file should have only one root element. | |
- element/attribute name shouldn’t contain space, shouldn’t contain special character and shouldn’t begin with number. | |
- attribute values must be placed inside double quotes. | |
- use XML entities to represent the following characters. | |
Character XML Entity | |
< < | |
> > | |
& & | |
‘ ' | |
“ &qout; | |
| |
- if any XML follows all the above rules that XML is called as wellformed XML, XML wellformness we can check by using browser. | |
Custom Rules : | |
- we can provide our own rules to the XML by using | |
DTD(Document type definition)/XSD(XML Schema definition). | |
- If any XML follows the custom rules that XML is called as Valid XML, every valid XML is a Wellformed XML can’t be vice versa. | |
- XML Validness we can check by using XML parsers (DOM,SAX,XML Pull Parsers). | |
UIGroup : | |
- UI Group to specify how to arrange the UI components. | |
- following are the major UI groups. | |
- Linear Layout | |
- Table Layout | |
- Relative Layout | |
- Constraint Layout | |
LinearLayout : | |
- LinearLayout is one of the UIgroup which is used to arrange the UI components in a vertical / horizontal direction one after another. | |
syntax : | |
<LinearLayout | |
xmlns:prefix = “xsd_location” | |
xmlns:android=“http://schemas.android.com/apk/res/android” | |
android:layout_width=“match_parent” | |
android:layout_height=“match_parent” | |
android:orientation=“vertical”> | |
<TextView | |
android:layout_width=“match_parent” | |
android:layout_height=“wrap_content” | |
android:text=“Welcome To NareshIT”/> </LinearLayout> | |
- for every UI component and UIgroup we have to specify width and height, following are the possible parameters to specify the width and height. | |
match_parent ( >= 2.2 ) | |
fill_parent ( < 2.2 ) | |
wrap_content | |
px [ pixel ] | |
dp [ density pixel ] | |
sp [ scaled pixel , only for textsize ] | |
- Steps to create an Activity (Kotlin file) : | |
- create a class as a child of android.app.Activity class. | |
(eg: class MainActivity : android.app.Activity( ) ) | |
- Activity Life Cycle : | |
- Activity is having 4 states. | |
1. Doesn’t Exist | |
2. Foreground | |
3. Pause | |
4. Background | |
- following are the major methods in Activity class. | |
- onCreate( ) - onPause( ) | |
- onStart( ) - onStop( ) | |
- onResume( ) - onRestart( ) | |
- onDestroy( ) | |
- every Activity will be maintained in Stack. | |
- to maintain Activity life cycle our class should be a child of android.app.Activity/AppCompactActivity class. | |
- same like main( ) method in C/C++/Java in Android Activity onCreate( ) method will be invoke first so provide the implementation for onCreate( ) method. | |
- use the following method to set the XML file to Kotlin file. | |
setContentView(R.layout.xml_file_name) | |
- Button is a click event, we can configure the click event in 2 ways. | |
- XML | |
- Kotlin | |
XML : | |
- to configure the click event using XML configure the following attribute to the UI component. | |
android:onClick=“functionName” | |
- if we click the button it will invoke the specified method in kotlin file, if the method is not available it will throw MethodNotFoundException. | |
eg : android:onClick=“getText” | |
fun getText(v:View){ | |
// function body… | |
} | |
- to get the UI component from XML to kotlin, we have configure an id for the component, use the following attribute to configure id. | |
android:id=“@+id/id_name” | |
- use the following in kotlin to get the component from XML. | |
findViewById(R.id.id_name) | |
- to configure the click event using kotlin, get the UI component from XML to kotlin. | |
ui_comp.setOnClickListener(object: View.OnClickListener | |
{ | |
fun onClick(v:View) { | |
// function body | |
} | |
}); | |
(or) | |
ui_comp.setOnClickListener{v:View | |
} | |
Intent : | |
- Intent is used to provide the communication between Activity - Activity, Activity - Service and Activity - Broadcast Receiver. | |
- In Android there are types of intents. | |
- Implicit Intent | |
- Explicit Intent | |
Implicit Intent : | |
- Implicit Intent is used to call builtin Activities. | |
(eg: Camera , Gallery , browser, dial,etc..) | |
syntax : | |
var i = Intent( ) | |
i.action = Intent.ACTION_NAME | |
startActivity(i) | |
Explicit Intent : | |
- Explicit Intent is used to call user defined activities. | |
syntax : | |
var i = Intent(context, ActivityName::class.java) | |
startActivity(i) | |
- by using explicit intents we can invoke other application activities. | |
syntax : | |
var i = packageManager.getLaunchIntentForPackage | |
(“package_name) | |
startActivity(i) | |
- following are the major methods in Intent class | |
setAction( ) putExtra( ) | |
setData( ) getExtra( ) | |
setType( ) | |
AutoCompleteTextView : | |
- ACTV is a child of EditText which is used to provide an auto completion support. | |
xml : | |
<AutoCompleteTextView | |
android:id=“@+id/actv” | |
…………………. /> | |
- to provide auto completion support we have to configure the values, In android there are 2 ways to configure the values. | |
- xml ( res >> values >> strings.xml ) | |
- kotlin ( array / collection ) | |
xml : | |
<string-array name=“array_name”> | |
<item> value1 </item> | |
<item> value2 </item> | |
………………… | |
</string-array> | |
- use the following method in kotlin to get the XML configured values. | |
var values:Array<String> = | |
getResources( ).getStringArray(R.array.array_name) | |
- kotlin : | |
var values = arrayOf<String>(value1,value2,value3..) | |
(or) | |
var values:MutableList<String> = mutableListOf<String>( ) | |
values.add(value1) | |
values.add(value2) | |
…………….. | |
- to present the data we have to create an adapter, In android there are 3 types of adapters. | |
- Array Adapter | |
- Custom Adapter | |
- Cursor Adapter | |
Array Adapter : | |
- ArrayAdapter is used to present String type of data. | |
syntax : | |
var myadapter = ArrayAdapter(context,xml_style,values) | |
actv.adapter = myadapter | |
actv.threshold = IntValue | |
Spinner : | |
- Spinner is one of the UI component in Android which is used to display the list of configured values in a drop down menu. | |
xml : <Spinner | |
android:id=“@+id/sp1” | |
…………………. /> | |
- same like ACTV to present the values we have to configure the values in XML/Kotlin, if the values are configured in XML use the following attribute to set the values. | |
android:entries=“@array/array_name” | |
- if the values are configured in kotlin , use adapter to present the values. | |
- Spinner is having item selected event, configure the following listener to get the selected item. | |
sp1.setOnItemSelectedListener( | |
object: OnItemSelectedListener{ | |
onItemSelected( ){…..} | |
onNothingSelected( ){…..} | |
}) | |
Toast : | |
Toast is one of the notification method in Android which is used to display text on the screen for few seconds. | |
syntax : | |
Toast.makeText( context, message, duration).show( ) | |
eg: | |
Toast.makeText(this@ActivityName, “Hello World”, | |
Toast.LENGTH_LONG/LENGTH_SHORT).show( ) | |
- to read the device external storage information we have to configure the following permission in Manifest.xml | |
<uses-permission android:name= | |
“android.permission.READ_EXTERNAL_STORAGE”/> | |
Runtime Permission : | |
- get the permission status. (make sure permission should be configured in Manifest.xml) | |
var status = ContextCompact.checkSelfPermission( | |
context, Manifest.permission.PERMISSION_NAME) | |
- check the permission status, if the permission is granted call readFiles( ) function, if the permission is not granted request the user to grant a permission. | |
if(status==PackageManager.PERMISSION_GRANTED) | |
{ | |
readFiles( ) | |
}else{ | |
ActivityCompact.requestPermission(context, | |
arrayOf<String>(Manifest.permission_name),req_code(int)) | |
} | |
- override the following method in Activity to know whether permission is granted/denied. | |
fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) | |
{ | |
if(grantResults[0]==PackageManager.PERMISSION_GRANTED) | |
{ | |
readFiles( ) | |
}else{ | |
Toast.makeText(this@MainActiivty, | |
“App can’t read storage info”,Toast.LENGTH_LONG).show( ) | |
} | |
} | |
- CustomAdapter : | |
- by using ArrayAdapter we can present only String type of data, to present your own UI on individual item use Custom Adapter. | |
- to create a custom adapter, create a class as a child of android.widget.BaseAdapter, it is an abstract class having abstract methods. | |
eg : class MyAdapter : BaseAdapter( ) | |
{ | |
fun getCount( ):Int | |
fun getItem( ):Any | |
fun getItemId( ):Any | |
fun getView( ):View | |
} | |
- LayoutInflater : LayoutInflater class is used to convert the XML file into View object. | |
var inflater = LayoutInflater.from(context) | |
var v:View = inflater.inflate(R.layout.xml_file, | |
view_group(optional-null)) | |
- ui_comp.setAdapter(CustomAdapterClassObject) | |
eg: lview.setAdapter(MyAdapter( )) method is used to set the custom adapter to the UI component. | |
WebView : | |
- Webview is one of the UI component in Android which is used to display webpages in Android application. ‘ | |
<Webview | |
android:id=“@+id/wview” | |
………………………. /> | |
- wview.loadUrl(url_address) method is used to display specified webpage on Webview. | |
- following are the major functionalities of webview | |
- call browser | |
- integrate browser | |
- display .html files | |
- communication between HTML UI | |
and Android Activity | |
http://www.flaticon.com | |
- use the following method to display webpage on Webview component. | |
wview.setWebViewClient(WebViewClient( )) | |
- following are the major methods in WebViewClient class. | |
onPageStarted( ) | |
shouldOverrideUrlLoading( ) | |
onPageFinished( ) | |
- set the following methods to webview to enable java script and zoom controls. | |
wview.settings.javaScriptEnable = true | |
wview.settings.builtinZoomControls = true | |
- to display html file on WebView, place the .html file in assets folder. | |
( app >> new >> folder >> assets folder ) | |
- wview.loadUrl(“file:///android_asset/file_name.html”) method is used to display webpage on WebView component. | |
Communication between HTML UI & Android Activity : | |
- by using JavaScript interface we can provide the communication between HTML and Activity (java/kotlin). | |
wview.addJavaScriptInterface(class_object,interface_name) | |
- by using second parameter(interface name) we can communicate with the specified class(specified in 1st param) methods from java script. | |
- which method you want to call from javascript, for that method add the following annotation. | |
@JavaScriptInterface | |
Fragment : | |
- Fragment is one of the UI component in Android. | |
(or) | |
- Fragment is called as subtype of an Activity. | |
xml : <fragment | |
android:id=“@+id/frag1” | |
android:name=“package_name.class_name” | |
………………… /> | |
- same like Activity every fragment is having its own UI [ xml file] and its own life cycle [kotlin file]. | |
- to create a fragment, create a class as a child of android.app.Fragment class. | |
- same like onCreate( ) method, in fragment onCreateView( ) method will be invoked first. | |
eg: class MyFragment : Fragment( ) | |
{ | |
fun onCreateView(inflater:LayoutInflater, | |
container:ViewGroup,b:Bundle):View | |
{ | |
var v = inflater.inflate(R.layout.xml_file,container,false) | |
return v; | |
} | |
} | |
- use the following code to manage fragments from Activity. | |
var fManager:FragmentManager = getSupportFragmentManager( ) | |
var tx:FragmentTransaction = fManager.beginTransaction( ) | |
tx.add/replace/remove(fragment_id,FragmentClassName( )) | |
tx.commit( ) | |
- if the UI component is available on fragment xml, we can’t configure the events (eg: click) using XML. | |
- fragment XML component we can access only its associate fragment kotlin file(not in Activity kotlin file). | |
- use the view object(inside onCreateView( ) function) to get the UI component from fragment xml file. | |
Storage Methods : | |
- Shared Preferences | |
- SQLite Database | |
- Files [ JSON ] | |
SharedPreferences : | |
- SPF is used to maintain the data in a key, value pair. | |
- SharedPreferences interface is used to manage SPF. | |
- getSharedPreferences(…) method is used to get the implementation class object of SharedPreferences. | |
var spf = getSharedPreferences(“pref_name”,Context.MODE) | |
- getSharedPreferences( ) is a Activity class method, use Activity object before calling this function in Fragment/Adapter. | |
- following are the possible parameters to specify mode. | |
- Context.MODE_PRIVATE | |
- Context.MODE_WORLD_READABLE | |
- Context.MODE_WORLD_WRITABLE | |
- if there is no spf is available with the specified name it will create a new SPF otherwise it will open connection with the existing SPF. | |
- by using above object(spf) we can create SPF and we can read the data from SPF, to write the data into SPF create an object for SharedPreferences.Editor. | |
var spe:SharedPreferences.Editor = spf.edit( ). | |
spe.putX(key, value) // X - data type | |
spe.commit( ) | |
- spf.getX(key,default_value) method is used to read the data from SPF, if the value is available with the specified key it will return the value from SPF otherwise it will return default value. | |
- spf internally will maintain the data in a xml file, we can explore the XML file using Android Device Monitor. | |
ADM >> file explorer >> data >> data >> package_name >> shared_prfs >> file_name.xml | |
- by using SPF we can maintain huge amount of data but for every value we have to specify a unique key its difficult to assign and remember keys thats why SPF is preferred to maintain small amount of data ( eg : pattern lock pin, keep me sign in credentials, game level completed , level highscore ,etc…), to maintain huge amount of data Android is recommend to use SQLite Database. | |
SQLite Database : | |
- SQLite database is used to maintain structured data in Android,SQLiteDatabase class is used to manage SQLite DB. | |
- openOrCreateDatabase(db_name,mode,cursor_factory) method is used get the object of SQLite Database. | |
var dBase = openOrCreateDatabase(“db_name”, | |
Context.MODE_PRIVATE,cursor_factory(null)) | |
- SQLite DB is providing builtin methods to perform CRUD operations. | |
- insert( ) | |
- query( ) // read | |
- update( ) | |
- delete( ) | |
- we can execute the native SQL statements by using following methods. | |
- execSQL(“sql_query”) // C I U D | |
- rawQuery(“sql_query”) // R | |
- we can explore the SQLite DB file using FileExplorer. | |
File explorer >> data >> data >> pkg_name >> database>> | |
file_name.db | |
- we can open the SQLite DB file using SQLite browser. | |
- if the data is available in a cursor , we can present the data on UI component by using SimpleCursorAdapter. | |
var adapter = SimpleCursorAdapter(context, xml_file, cursor_object, from ( String[ ] - column names), | |
to( int[ ] - id’s of the UI components ),flag(0) ) | |
Steps to Achieve MVP Design Pattern : | |
- create a project, create following packages as a child packages under the root package. | |
- view | |
- model | |
- presenter | |
- beans | |
- move Activity/Fragment files into view package. | |
- create equalant bean classes based on SQLite table / web service response under beans package. | |
data class IncExpBean(var date:String, var money:Int, | |
var desc:String, var type:String) | |
- create an interface under view package , interface should contain an abstract functions for presentation of data. | |
- Activity class / Fragment class has to provide the implementation for ViewAPI interface. | |
- create an interface under presenter package, interface should contain an abstract functions for user input. | |
- create a class under model package, the class has to provide the implementation for PresenterAPI interface, the model class should contain a constructor which is taking ViewAPI interface as a input parameter. | |
Android Telephony : | |
- SMS | |
- Call | |
- Builtin Activity | |
- AsyncTask | |
- Java Mail API | |
SMS : | |
- android.telephony.SmsManager class is used to send text messages in Android. | |
var sManager = SmsManager.getDefault( ) | |
sManager.sendTextMessage(dest_num, source_num, | |
message, send_intent , deliver_intent) | |
above method is used to send text message in Android. | |
permission : | |
SEND_SMS | |
PendingIntent : PendingIntent is a child of Intent which is called by later. | |
syntax : | |
var i = Intent(context,ActivityName:class.java) | |
var pIntent = PendingIntent.getActivity(context, | |
request_code(0), intent_object, request_flag(0)) | |
Call : | |
Android is providing a builtin Activity for making calls, use implicit intents to call builtin Activity. | |
var i = Intent( ) | |
i.setAction(Intent.ACTION_CALL) | |
i.setData(Uri.parse(“tel:”+number)) | |
startActivity(i) | |
permission : | |
CALL_PHONE | |
Email : | |
- for sending an email Android is providing a builtin Activity use implicit intents to call builtin Activity. | |
var i = Intent( ) | |
i.setAction(Intent.ACTION_SEND) | |
i.putExtra(Intent.EXTRA_EMAIL,arrayOf<mail1,mail2..>) | |
i.putExtra(Intent.EXTRA_SUBJECT,”subject_here”) | |
i.putExtra(Intent.EXTRA_TEXT,”message here”) | |
i.putExtra(Intent.EXTRA_STREAM,uri_object) //attachment | |
i.setType(“message/rfc822”) // enable MIME type startActivity(i) | |
permission : | |
INTERNET | |
Attachment : | |
Camera : | |
var i = Intent(“android.media.action.IMAGE_CAPTURE”) | |
startActivityForResult(i,request_code(positive_integer)) | |
Gallery / File Explorer : | |
var i = Intent( ) | |
i.setAction(Intent.ACTION_GET_CONTENT) | |
i.setType(“*/*”) | |
startActivityForResult(i,request_code(positive_integer)) | |
in above method ( startActivityForResult( )), if we specify the second parameter (request_code) >= 0 after the next Activity is completed it will invoke the following method in current Activity. | |
fun onActivityResult(request_code:Int, result_code:Int, | |
data:Intent) | |
{ | |
if(request_code == camera && result_code == RESULT_OK) | |
{ | |
var obj:Object = data.getExtra( ).get(“data”) | |
}else if(request_code == gallery && result_code == RESULT_OK ) | |
{ | |
var uri = data.getData( ) | |
} | |
} | |
permissions: | |
CAMERA | |
WRITE_EXTERNAL_STORAGE | |
- by using builtin Activity we can’t send a mail in the background user has to select any one of the email client application (gmail, email…) to send a mail, to send a mail in the background with out any user interaction use Java Mail API. | |
Steps to work with Java Mail API : | |
- create a project, add the following .jar files as a modules. | |
(right click on app>>new>>module>>import jar>>select jar) | |
- activation.jar | |
- additional.jar | |
- mail.jar | |
- add the above modules as a dependency modules for the application. | |
( right click on app >> module settings >> dependencies >> | |
+ >> module dependency >> select module ) | |
- copy the following .java files into project package folder. | |
- GmailSender.java | |
- JSSEProvider.java | |
- LongOperation.java | |
- configure the from mail credentials in LongOperation.java | |
- execute the LongOperation from Activity. | |
var lop = LongOperation( to_mail_id,subject,message) | |
lop.execute( ) | |
- LongOperation is an AsyncTask[?]. | |
AsyncTask : | |
- in Android every Activity will run on a Thread called UIThread / Activity Thread. | |
- Thread is a separate process on JVM/DVM to perform a specific task. | |
- if we execute long operations (network calls ) on Activity Thread, the Activity will freeze this is also called as ANR state (application not responding state). | |
- to avoid ANR state execute the long operations on a separate Thread ( we can’t communicate with Activity UI components from separate Thread) or execute the long operations (network calls) in background on Activity Thread by using AsyncTask. | |
Steps to create an AsyncTask : | |
- create a class as a child of | |
android.os.AsyncTask<param1,param2,param3> | |
- it is an abstarct class having an abstract method called doInBackground( ). | |
- following are the major methods in AsyncTask. | |
- onPreExecute( ) | |
- doInBackground( ) | |
- onPostExecute( ) | |
- if we are using AsyncTask in Activity, add the following statements in onCreate( ) method. | |
var policy:ThreadPolicty = StrictMode.ThreadPolicy.Builder(context).permitAll( ).build( ) | |
StrictMode.setThreadPolicy(policy) | |
- use the following code to execute the AsyncTask. | |
var task = AsyncTaskName( ) | |
task.execute( ) | |
Service : | |
- A long running background process with out any user interaction is called as Service. | |
Steps to work with Service : | |
- to create a service , create a class as a child of android.app.Service class. | |
- it is an abstarct class having an abstarct method called onBind( ), so provide the implementation for onBind( ) | |
- following are the major methods in Service class. | |
- onCreate( ) | |
- onStartCommand( ) | |
- onDestroy( ) | |
- when we start a service if the service is not available in a stack it will invoke onCreate( ) and onStartCommand( ) methods. | |
- if the service is already available in a stack it will invoke only onStartCommand( ) method. | |
- when we stop the service it will invoke onDestroy( ) | |
- Service doesn’t contain UI, we will manage service from activity by using Intent. | |
var i = Intent(context, ServiceName::class.java) | |
startService(i) | |
stopService(i) | |
- same like Activity every service has to be configured in Manifest.xml with the following tag inside <application> tag. | |
<service android:name=“package_name.ServiceClassName”/> | |
Broadcast Receiver : | |
- by using broadcast receiver we can get the system events and we can fire our own broadcast events. | |
(eg : headset plugin, power connected/disconnected, screen on/off, making/receiving call , battery low/full/dead, phone restarted/shutdown , open wifi n/w available, new BT device is found , etc ) | |
- by using BR we can fire our own events using sendBroadcast(intent_obj) method. | |
Steps to get the broadcast events : | |
- create a class as a child of android.content.BroadcastReceiver. | |
- this is an abstract class having an abstract method called onReceive(context,intent_obj) . | |
- from Activity/Service for which events you want to get the broadcast announcements configure the events using IntentFilter(group of intents is called as IntentFilter). | |
var intent_filter = IntentFilter( ) | |
intent_filter.addAction(Intent.ACTION_NAME) | |
………………………… | |
registerReceiver(object_of_BR, intent_filter) | |
- if any one of the configured events are happened it will invoke onReceive( ) method of broadcast receiver class. | |
Intent Service : | |
- Intent Service is a child of Service, which will stop once the background execution is done by calling selfStop( ) method. | |
- IntentService is an alternative for AsyncTask, AsyncTask will run in the background on Activity Thread, if we destroy Activity AsyncTask also will be destroyed. | |
- IntentService will run on a separate Thread, if we destroy activity/application Intent Service still will run in the background, we can communicate with Activity from IntentService by using Broadcast Receiver. | |
- to create an IntentService, create a class as a child of android.app.IntentService , it is an abstarct class having an abstarct function called onHandleIntent( ). | |
- every service class should be configured in Manifest.xml with the following tag inside <application> tag. | |
<service android:name=“.ServiceName”/> | |
Builtin Services : | |
- Location Service - Bluetooth | |
- Notification Service - Vibrator - Sensor Service - Telephony Service | |
- Wifi Service - Connectivity Service | |
Location Service : | |
- getSystemService(Context.LOCATION_SERVICE) method is used to get the builtin location service, application framework is providing a class called LocationManager to manage location service. | |
var lManager:LocationManager = getSystemService( | |
Context.LOCATION_SERVICE) as LocationManager | |
- lManager.getLastKnownLocation( | |
LocationManager.PROVIDER_NAME) | |
method is used to get the last updated location. | |
- to get the current updated location configure the following listener. | |
lManager.requestLocationUpdates(PROVIDER_NAME, | |
minimum_time(ms), minimum_distance(meters), | |
object: LocationListener( ){ | |
fun onLocationChanged(l:Location){ | |
var lati = l.getLatitude( ) | |
var longi = l.getLongitude( ) | |
} | |
// ……………………………. | |
}) | |
permissions : | |
ACCESS_FINE_LOCATION | |
ACCESS_COARSE_LOCATION | |
Vibrator : | |
- getSystemService(Context.VIBRATOR_SERVICE) | |
method is used to get the builtin vibrator service, application framework is providing a class called Vibrator to manage vibrate service. | |
var vib:Vibrator = getSystemService( | |
Context.VIBRATOR_SERVICE) as Vibrator | |
vib.vibrate(milli_seconds) | |
permissions : | |
VIBRATE | |
Notification Service : | |
var nManager:NotificationManager = getSystemService( | |
Context.NOTIFICATION_SERVICE) as NotificationManager | |
- to display notification on notification bar/status bar use the following code. | |
var notification = NotificationCompact.Builder(context,channel_id) | |
notification.setTickerText(“ticker_text”) | |
notification.setSmallIcon(R.drawable.image_name) | |
notification.setLargeIcon(bitmap_object) notification.setContentTitle(“content_title_here”) | |
notification.setContentText(“text_here”) notification.setAutoCancel(true) notification.setContentIntent(pending_intent_object) | |
nManager.notify(notification.build( ), notification_id(int)) | |
Sensor Service : | |
- In android based on the device capability there are different types of sensors. | |
- ACCESSOLORY | |
- PROXIMITY | |
- GYROSCOPE | |
- TEMPRATURE | |
- getSystemService(Context.SENSOR_SERVICE) method is used to get the builtin service, application f/w is providing a class called SensorManager to manage sensor service. | |
var sManager = getSystemService( | |
Context.SENSOR_SERVICE) as SensorManager | |
- configure the following listener to get the sensor events. | |
var s:Sensor = sManager.getDefaultSensor( | |
Sensor.SENSOR_NAME) | |
- sManager.registerListener( object:SensorEventListener( ){ | |
fun onSensorChanged( …..) { } | |
}, sensor_object, speed) | |
permissions : | |
<uses-feature | |
android:name="android.hardware.sensor.proximity" | |
android:required="true" /> | |
<uses-feature | |
android:name="android.hardware.sensor.gyroscope" | |
android:required="true" /> | |
Wifi Service : | |
- getSystemService(Context.WIFI_SERVICE) method is used to get the builtin wifi service, application framework is providing a class called WifiManager to manage wifi service. | |
var wManager = applicationContext.getSystemService( | |
Context.WIFI_SERVICE) as WifiManager | |
- wManager.getWifiState( ) method is used to get the wifi state, return type of this function is int(0-disabled, 1-disabling , 2- enabling , 3-enabled ) | |
- wManager.setWifiEnabled(boolean) method is used to change the wifi state. | |
- wManager.getScanResults( ) method is used to get the list of available wifi devices, return type of this method is List<ScanResult>. | |
var list:List<ScanResult> = wManager.getScanResults( ) | |
for(result in list){ | |
result.SSID // to get network name | |
result.frequency // to get single strength | |
} | |
- wManager.getConfiguredNetworks( ) method is used to get the list of paired wifi devices. | |
var list:List<WifiConfiguration> = | |
wManager.getConfiguredNetworks( ) | |
for(result in list) | |
{ | |
result.SSID // to get network name | |
result.status // to get network status | |
} | |
permissions : | |
ACCESS_WIFI_STATE | |
CHANGE_WIFI_STATE | |
ACCESS_COARSE_LOCATION | |
Bluetooth Service : | |
- In android there are different ways to manage Bluetooth service, one of the best approach is manage BT service using BluetoothAdapter. | |
var bAdapter = BluetoothAdapter.getDefault( ) | |
- bAdapter.isEnabled( ) method is used to get the BT state. | |
- bAdapter.enable( ) / disable( ) methods is used to change | |
the BT state. | |
- to get the list of available BT devices we have to configure | |
a Broadcast receiver. | |
bAdapter.startDiscovery( ) | |
var filter = IntentFilter( ) | |
filter.addAction(BluetoothDevice.ACTION_FOUND) | |
registerReceiver(object:BroadcastReceiver( ){ | |
fun onReceive(c:Context, data:Intent){ | |
var bt_device = data.getParcableExtra( | |
BluetoothDevice.EXTRA_DEVICE) | |
bt_device.name; bt_device.address | |
} }, filter) | |
permission : | |
BLUETOOTH | |
BLUETOOTH_ADMIN | |
ACCESS_COARSE_LOCATION | |
Telephony Service : | |
var tManager : TelephonyManager = getSystemService( | |
Context.TELEPHONY_SERVICE) as TelephonyManager | |
following the major methods in Telephony manager class. | |
Connectivity Service : | |
- Connectivity service is used to access whether device data is enabled / disabled. | |
var cManager : ConnectivityManager = getSystemService( | |
Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
permissioss: READ_PHONE_STATE | |
ACCESS_NETWORK_STATE | |
Content Provider : | |
- Content Provider is used to share the data between multiple applications. ( In Android one of the security feature is which application is created the database the complete rights on the database belongs to that application, other applications can’t access the data , but if the application is providing content provider then it is possible to access the data, In android following builtin applications are providing content provider | |
Contacts , callog , media , settings , calendar , messages ). | |
Steps to work with Content Provider : | |
- to read the data from CP, we have to get an object for ContentResolver class. | |
var resolver:ContentResolver = getContentResolver( ) | |
- resolver.query(CP_URI, projection, selection, selectionArgs, sort_order) return type of this method Cursor. | |
- if the data is available in a cursor for presenting the data Android is providing an adapter called SimpleCursorAdapter. | |
var adapter = SimpleCursorAdapter(context, xml_file, | |
cursor_object, from, to) | |
ui_comp.setAdapter(adapter) | |
Contacts : ContactsContract.CommonDataKinds.Phone.CONTENT_URI | |
CallLog : CallLog.Calls.CONTENT_URI | |
Msgs : "content://sms/inbox" | |
Advanced Android : | |
- WebServices | |
- JSON | |
- GSON | |
- Rest WebServices | |
- Retrofit | |
- Firebase | |
- Authentication | |
- Database | |
- Storage | |
- Cloud Messaging | |
- Admob | |
- MLKit | |
- Google API’s | |
- Google Maps | |
- Google Places | |
- Material Design | |
[ RecyclerView,CardView, Floating Action Button, | |
Snack Bar, Navigation Drawer , View Pager , | |
Tabbed Activity ] | |
- Flutter | |
Web Services : | |
- Web Services is used to provide the communication between 2 applications, the 2 applications can be developed by using same programming language / different language. | |
- It uses an interoperable format ( platform indipendent & language independent ) to transfer the data between applications. (XML , JSON , CSV, .txt these are sample interoperable formats) | |
- There are 2 types of Web Services. | |
- SOAP [ Simple Object Access Protocol ] | |
- REST [ Representational State Transfer ] | |
REST WebServices communication using Retrofit : | |
- create a project add the following libraries as a dependency libraries. | |
- GSON | |
- Retrofit | |
- Retrofit-GSON converter. | |
- create the equalant bean/data class based on JSON response. | |
- create an interface, interface should contain abstarct methods, return type of the abstract method should be Call<MainBeanClass>. | |
- on top of the interface abstarct method specify the request type and configure the sub-url. | |
e.g.: | |
interface RailwayAPI { | |
@GET("v2/live/train/17405/date/26-10-2018/apikey/3us4nq7cyl/") | |
fun getTrainStatus():Call<TrainStatusBean> | |
} | |
- initialize retrofit object in Activity. | |
var r = Retrofit.Builder(). | |
addConverterFactory(GsonConverterFactory.create()). | |
baseUrl("https://api.railwayapi.com/"). | |
build() | |
- provide an implementation for interface. | |
var api:RailwayAPI = r.create(RailwayAPI::class.java) | |
- call the abstarct function of interface. | |
var call:Call<TrainStatusBean> = api.getTrainStatus() | |
- use the following code to make REST Webservice request using retrofit. | |
call.enqueue(object:Callback<TrainStatusBean>{ | |
override fun onFailure(call: Call<TrainStatusBean>, t: Throwable) { | |
} | |
override fun onResponse(call: Call<TrainStatusBean>, response: Response<TrainStatusBean>) { | |
} | |
}) | |
permissions : | |
INTERNET | |
Steps to work with Google Maps : | |
- create a project, add play-services:maps library project as a dependency project. | |
- in the activity xml file, create a <fragment> UI component with the following name. | |
<fragment | |
android:id=“@+id/frag1” | |
android:name=“com.google.android.gms.maps.SupportMapFragment” | |
…………….. /> | |
- get the SupportMapFragment from XML to kotlin file. | |
var frag:SupportMapFragment = getSupportFragmentManager(). | |
findFragmentById(R.id.frag1) | |
as SupportMapFragment | |
- get the GoogleMap object from SupportMapFragment. | |
frag.getMapAsync(object:onMapReadyCallback{ | |
override fun onMapReady(gMap:GoogleMap) | |
{ | |
// method will be triggered when GoogleMap ready | |
} | |
}) | |
- to work with any GoogleAPI (eg: Maps,Places, youtube , google drive, gmail, directions, firebase , etc) we have to get an API key from Google, go through the following URL to get the API key. | |
http://code.google.com/apis/console | |
- create a project >> enable maps sdk for Android >> credentials >> create credentials >> API key | |
- configure the API key in Manifest.xml with the following tag inside <application> tag. | |
<meta-data | |
android:name=“com.google.android.geo.API_KEY” | |
android:value=“YOUR_API_KEY”/> | |
- use the following code to change the map style. | |
gMap!!.mapType = GoogleMap.MAP_TYPE_SATELLITE | |
- use the following code to place a location on the Map. | |
var options:MarkerOptions = MarkerOptions( ) | |
options.position(LatLng(latitude, longitude)) | |
gMap.addMarker(options) | |
- use the following method to move & zoom the camera ( max zoom is 25 ) | |
gMap.animateCamera(CameraUpdateFactory. | |
newLatLngZoom(LatLng(lati,longi),15.toFloat())) | |
- to customize the marker place the image in drawable folder with .png format. | |
- use the following code to set the image as a marker. | |
options.icon(BitmapDescriptorFactory. | |
fromResource(R.drawable.car)) | |
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=17.439262,78.4487428&radius=1500&type=restaurant&key=AIzaSyDdCGdR2cnWw0AB0LeN3jOTjKmkKa | |
g4tew | |
Place Picker : | |
- add the following libraries as a dependency libraries | |
implementation 'com.google.android.gms:play-services-location:15.0.1' | |
implementation 'com.google.android.gms:play-services-places:15.0.1' | |
implementation 'com.google.android.gms:play-services-maps:15.0.1' | |
implementation 'com.squareup.retrofit2:retrofit:2.4.0' | |
implementation 'com.google.code.gson:gson:2.8.5' | |
implementation 'com.squareup.retrofit2:converter-gson:2.4.0' | |
http://10.0.0.2:8080/And7AMNov/stu.apk | |
Material Design : | |
- RecyclerView & CardView | |
- Floating Action Button | |
- Snack Bar | |
- Toolbar & Menu | |
- Navigation Drawer | |
- Tabbed Activity / View Pager | |
RecyclerView & CardView : | |
limitations of custom adapter : | |
- for individual item custom adapter will load the xml file and will inflate (convert xml into view object) the xml file. | |
- because of this the performance will be less with custom adapter. | |
- we have to use ListView to present the data in vertical format, Gallery in horizontal format and GridView in Grid Format. | |
- by using RecyclerView we can present the data in vertical/horizontal/grid format. | |
- RecyclerView is providing RecyclerView adapter to present the data, RecyclerAdapter will load and inflate the XML only once. | |
Steps to work with RecyclerView & CardView : | |
- create a project, add the following libraries as a dependency libraries. | |
implementation 'com.android.support:recyclerview-v7:28.0.0' | |
implementation 'com.android.support:cardview-v7:28.0.0' | |
- create a RecyclerView UI component in Activity XML file. | |
<android.support.v7.widget.RecyclerView | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
android:id="@+id/rview"/> | |
- get the RecyclerView component into Activity, set the LayoutManager (vertical|horizontal|grid) in which format you want to present the data. | |
var lManager = LinearLayoutManager( | |
this@MainActivity, | |
LinearLayoutManager.VERTICAL,false) | |
var gManager = GridLayoutManager( | |
this@MainActivity,2) | |
rview.layoutManager = lManager // (0r) gManager | |
- create an XML file in which format you want to present the individual item (to get more look & feel create an XML file with CardView as a root UI group). | |
- create a holder class, to hold the UI components of individual XML file. | |
- to create holder class, create a class as a child of RecyclerView.ViewHolder. | |
- create an Adapter class, to create adapter create a class as a child of RecyclerView.Adapter<ViewHolderClass> | |
- it is an abstract class having 3 abstract functions. | |
- onCreateViewHolder(..):HolderClass | |
- onBindViewHolder(HolderClass) | |
- getItemCount( ): Int | |
- use the following code to set the adapter to recycler view. | |
rview.adapter = RecyclerViewAdapter | |
ClassName( ) | |
Floating Action Button : | |
- to create Floating Action add design library as a dependency library. | |
implementation 'com.android.support:design:28.0.0' | |
- to use FAB , the root UI group must be CoordinatorLayout. | |
Snack Bar : | |
ToolBar : | |
- by default Activity contains a Toolbar, to customise the Toolbar add design library as a dependency library. | |
implementation 'com.android.support:design:28.0.0' | |
- supportActionBar!!.setTitle("Naresh IT") | |
Menu : | |
- to display menu options, configure the menu options in the following XML file. | |
res >> menu >> file_name.xml | |
<menu> | |
<item android:title=“title_here” | |
android:icon= “@drawable/icon”/> | |
<item…./> | |
<item…./> | |
<item> | |
<menu> | |
<item…./> | |
<item…/> | |
</menu> | |
</item> | |
</menu> | |
- override the following method to display menu options. | |
override fun onCreateOptionsMenu(m:Menu) | |
{ | |
getMenuInflater().inflate(R.menu.xml_file,menu_obj) | |
} | |
- if we select any menu item it will invoke the following method. | |
override fun onOptionsItemSelected(item:MenuItem) | |
{ | |
// code to execute when menu item clicked.. | |
} | |
- use the following attribute to display menu options in Toolbar. | |
app:showAsAction=“always|ifRoom|never” | |
Firebase : | |
- Auth , DB , Storage , Admob , MLKit, FCM | |
Flutter : | |
http://flutter.io | |
- download FlutterSDK | |
- Add Flutter Plugin in Android Studio | |
- while creating a project in Android Studio select create a new flutter project. | |
- specify the flutter SDK location. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment