0% found this document useful (0 votes)
15 views80 pages

UNIT 4 Android

The document provides an overview of integrating Google Maps into Android applications, detailing the types of maps available (Normal, Hybrid, Satellite, Terrain, and None) and their respective syntax. It also outlines methods for customizing the Google Map, along with example code for implementing a Google Map and managing user permissions in AndroidManifest.xml. Additionally, it touches on enabling and disabling Wi-Fi and creating notifications in Android, including sample code for each functionality.

Uploaded by

adityakumawat625
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views80 pages

UNIT 4 Android

The document provides an overview of integrating Google Maps into Android applications, detailing the types of maps available (Normal, Hybrid, Satellite, Terrain, and None) and their respective syntax. It also outlines methods for customizing the Google Map, along with example code for implementing a Google Map and managing user permissions in AndroidManifest.xml. Additionally, it touches on enabling and disabling Wi-Fi and creating notifications in Android, including sample code for each functionality.

Uploaded by

adityakumawat625
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Android Google Map

Android provides facility to integrate Google map in our application. Google map
displays your current location, navigate location direction, search location etc. We can
also customize Google map according to our requirement.

Types of Google Maps


There are four different types of Google maps, as well as an optional to no map at all.
Each of them gives different view on map. These maps are as follow:

1. Normal: This type of map displays typical road map, natural features like river and some
features build by humans.
2. Hybrid: This type of map displays satellite photograph data with typical road maps. It
also displays road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display road and
feature labels.
4. Terrain: This type displays photographic data. This includes colors, contour lines and
labels and perspective shading.
5. None: This type displays an empty grid with no tiles loaded.

Syntax of different types of map


1. googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
2. googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
3. googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
4. googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Methods of Google map

Google map API provides several methods that help to customize Google map. These methods
are as following:

Description Methods
This method add circle to map. addCircle(CircleOptions options)

This method add polygon to map. addPolygon(PolygonOptions options)

This method add tile overlay to the map. addTileOverlay(TileOverlayOptions options)

This method moves the map according to the animateCamera(CameraUpdate update)


update with an animation.

This method removes everything from the map. clear()

This method returns the currently displayed user getMyLocation()


location.

This method reposition the camera according to the moveCamera(CameraUpdate update)


instructions defined in the update.

This method set the traffic layer on or off. setTrafficEnabled(boolean enabled)

This method takes a snapshot of the map. snapshot(GoogleMap.SnapshotReadyCallback


callback)

This method stops the camera animation if there is stopAnimation()


any progress.

Example of Google Map


Let's create an example of Google map integrating within our app. For doing this we
select Google Maps Activity.
Copy the URL from google_map_api.xml file to generate Google map key.

Paste the copied URL at the browser. It will open the following page.
After clicking on Create API key, it will generate our API key displaying the following screen.
Copy this generated API key in our google_map_api.xml file

activity_maps.xml
1. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:map="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:id="@+id/map"
5. android:name="com.google.android.gms.maps.SupportMapFragment"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. tools:context="example.com.mapexample.MapsActivity" />
MapsActivity.java
To get the GoogleMap object in our MapsActivity.java class we need to implement the
OnMapReadyCallback interface and override the onMapReady() callback method.

1. package example.com.mapexample;
2.
3. import android.support.v4.app.FragmentActivity;
4. import android.os.Bundle;
5. import com.google.android.gms.maps.CameraUpdateFactory;
6. import com.google.android.gms.maps.GoogleMap;
7. import com.google.android.gms.maps.OnMapReadyCallback;
8. import com.google.android.gms.maps.SupportMapFragment;
9. import com.google.android.gms.maps.model.LatLng;
10. import com.google.android.gms.maps.model.MarkerOptions;
11.
12. public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
13.
14. private GoogleMap mMap;
15.
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_maps);
20. // Obtain the SupportMapFragment and get notified when the map is ready to be used.
21. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentMana
ger()
22. .findFragmentById(R.id.map);
23. mapFragment.getMapAsync(this);
24.
25. }
26.
27. @Override
28. public void onMapReady(GoogleMap googleMap) {
29. mMap = googleMap;
30.
31. // Add a marker in Sydney and move the camera
32. LatLng sydney = new LatLng(-34, 151);
33. mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
34. mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
35.
36. }
37. }

Required Permission
Add the following user-permission in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
3. <uses-permission android:name="android.permission.INTERNET" />

AndroidManifest.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.com.mapexample">
4. <!--
5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
6. Google Maps Android API v2, but you must specify either coarse or fine
7. location permissions for the 'MyLocation' functionality.
8. -->
9. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
10. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@mipmap/ic_launcher"
16. android:label="@string/app_name"
17. android:roundIcon="@mipmap/ic_launcher_round"
18. android:supportsRtl="true"
19. android:theme="@style/AppTheme">
20.
21. <meta-data
22. android:name="com.google.android.geo.API_KEY"
23. android:value="@string/google_maps_key" />
24.
25. <activity
26. android:name=".MapsActivity"
27. android:label="@string/title_activity_maps">
28. <intent-filter>
29. <action android:name="android.intent.action.MAIN" />
30.
31. <category android:name="android.intent.category.LAUNCHER" />
32. </intent-filter>
33. </activity>
34. </application>
35.
36. </manifest>

build.gradel
Add the following dependencies in build.gradel file.

1. dependencies {
2. implementation fileTree(dir: 'libs', include: ['*.jar'])
3. implementation 'com.android.support:appcompat-v7:26.1.0'
4. implementation 'com.google.android.gms:play-services-maps:11.8.0'
5. testImplementation 'junit:junit:4.12'
6. androidTestImplementation 'com.android.support.test:runner:1.0.1'
7. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
8. }

Output
Android Wifi Example
The android.net.wifi.WifiManager class can be used to manage the wifi connectivity. It
can be used to add network, disable network, scan for access points, disconnect etc.

Android wifi example to enable and disable wifi


Let's see the simple example of wifi to enable and disable the wifi service.

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="76dp"
14. android:layout_marginTop="67dp"
15. android:text="Enable Wifi" />
16.
17. <Button
18. android:id="@+id/button2"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:layout_alignLeft="@+id/button1"
22. android:layout_below="@+id/button1"
23. android:layout_marginTop="44dp"
24. android:text="Disable Wifi" />
25.
26. </RelativeLayout>

Activity class
File: MainActivity.java

1. package com.example.wifi;
2.
3. import android.net.wifi.WifiManager;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.content.Context;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button enableButton,disableButton;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. enableButton=(Button)findViewById(R.id.button1);
20. disableButton=(Button)findViewById(R.id.button2);
21.
22. enableButton.setOnClickListener(new OnClickListener(){
23. public void onClick(View v){
24. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
25. wifi.setWifiEnabled(true);
26. }
27. });
28. disableButton.setOnClickListener(new OnClickListener(){
29. public void onClick(View v){
30. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
31. wifi.setWifiEnabled(false);
32. }
33. });
34. }
35.
36. @Override
37. public boolean onCreateOptionsMenu(Menu menu) {
38. // Inflate the menu; this adds items to the action bar if it is present.
39. getMenuInflater().inflate(R.menu.activity_main, menu);
40. return true;
41. }
42.
43. }

Add Permission in AndroidManifest.xml

You need to add following permissions in AndroidManifest.xml file.

Play Video

1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


2. <uses-permission android:name="android.permission.INTERNET" />
3. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
Output:

Android Notification
Android Notification provides short, timely information about the action happened in
the application, even it is not running. The notification displays the icon, title and some
amount of the content text.

Set Android Notification Properties


The properties of Android notification are set
using NotificationCompat.Builder object. Some of the notification properties are
mention below:

o setSmallIcon(): It sets the icon of notification.


o setContentTitle(): It is used to set the title of notification.
o setContentText(): It is used to set the text message.
o setAutoCancel(): It sets the cancelable property of notification.
o setPriority(): It sets the priority of notification.
Android Notification Example
In this example, we will create a notification message which will launch another activity
after clicking on it.

activity_main.xml
Add the following code in an activity_main.xml file.

Play Video

1. <?xml version="1.0" encoding="utf-8"?>


2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidnotification.MainActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="ANDROID NOTIFICATION"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent"
17. app:layout_constraintVertical_bias="0.091"
18. android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
19.
20. <Button
21. android:layout_width="wrap_content"
22. android:layout_height="wrap_content"
23. android:id="@+id/button"
24. android:layout_marginBottom="112dp"
25. android:layout_marginEnd="8dp"
26. android:layout_marginStart="8dp"
27. android:text="Notify"
28. app:layout_constraintBottom_toBottomOf="parent"
29. app:layout_constraintEnd_toEndOf="parent"
30. app:layout_constraintStart_toStartOf="parent" />
31.
32. </android.support.constraint.ConstraintLayout>

Create an activity named as activity_notification_view.xml and add the following code.


This activity will be launched on clicking the notification. TextView is used to display the
notification message.

activity_notification_view.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidnotification.NotificationView">
8.
9. <TextView
10. android:id="@+id/textView2"
11. android:layout_width="fill_parent"
12. android:layout_height="wrap_content"
13. android:gravity="center"
14. android:text="your detail of notification..."
15. android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
16.
17. <TextView
18. android:id="@+id/textView"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:layout_marginBottom="8dp"
22. android:layout_marginEnd="8dp"
23. android:layout_marginStart="8dp"
24. android:layout_marginTop="8dp"
25. app:layout_constraintBottom_toBottomOf="parent"
26. app:layout_constraintEnd_toEndOf="parent"
27. app:layout_constraintHorizontal_bias="0.096"
28. app:layout_constraintStart_toStartOf="parent"
29. app:layout_constraintTop_toBottomOf="@+id/textView2"
30. app:layout_constraintVertical_bias="0.206"
31. android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
32.
33. </android.support.constraint.ConstraintLayout>

MainActivity.java
In the MainActivity.java class adds the following code. In this class, clicking the button
calls the addNotification() method where we implement the NotificationCompat.Builder
object to set the notification properties. The NotificationManager.notify() method is
used to display the notification. The Intent class is used to call another activity
(NotificationView.java) on taping the notification.

1. package example.javatpoint.com.androidnotification;
2.
3. import android.app.NotificationManager;
4. import android.app.PendingIntent;
5. import android.content.Context;
6. import android.content.Intent;
7. import android.support.v4.app.NotificationCompat;
8. import android.support.v7.app.AppCompatActivity;
9. import android.os.Bundle;
10. import android.view.View;
11. import android.widget.Button;
12.
13. public class MainActivity extends AppCompatActivity {
14. Button button;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19. button = findViewById(R.id.button);
20. button.setOnClickListener(new View.OnClickListener() {
21. @Override
22. public void onClick(View v) {
23. addNotification();
24. }
25. });
26. }
27.
28. private void addNotification() {
29. NotificationCompat.Builder builder =
30. new NotificationCompat.Builder(this)
31. .setSmallIcon(R.drawable.messageicon) //set icon for notification
32. .setContentTitle("Notifications Example") //set title of notification
33. .setContentText("This is a notification message")//this is notification message
34. .setAutoCancel(true) // makes auto cancel of notification
35. .setPriority(NotificationCompat.PRIORITY_DEFAULT); //set priority of notification
36.
37.
38. Intent notificationIntent = new Intent(this, NotificationView.class);
39. notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
40. //notification message will get at NotificationView
41. notificationIntent.putExtra("message", "This is a notification message");
42.
43. PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
44. PendingIntent.FLAG_UPDATE_CURRENT);
45. builder.setContentIntent(pendingIntent);
46.
47. // Add as notification
48. NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFIC
ATION_SERVICE);
49. manager.notify(0, builder.build());
50. }
51. }

NotificationView.java
The NotificationView.java class receives the notification message and is displayed in
TextView. This class is invoked while taping the notification.

1. package example.javatpoint.com.androidnotification;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.TextView;
6. import android.widget.Toast;
7.
8. public class NotificationView extends AppCompatActivity {
9. TextView textView;
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_notification_view);
14. textView = findViewById(R.id.textView);
15. //getting the notification message
16. String message=getIntent().getStringExtra("message");
17. textView.setText(message);
18. }
19. }

strings.xml
1. <resources>
2. <string name="app_name">AndroidNotification</string>
3. <string name="notification_activity">NotificationView</string>
4. </resources>
AndroidManifest.xml
Add the following code in AndroidManifest.xml file.

1. <?xml version="1.0" encoding="utf-8"?>


2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.javatpoint.com.androidnotification">
4.
5. <application
6. android:allowBackup="true"
7. android:icon="@mipmap/ic_launcher"
8. android:label="@string/app_name"
9. android:roundIcon="@mipmap/ic_launcher_round"
10. android:supportsRtl="true"
11. android:theme="@style/AppTheme">
12. <activity android:name=".MainActivity">
13. <intent-filter>
14. <action android:name="android.intent.action.MAIN" />
15.
16. <category android:name="android.intent.category.LAUNCHER" />
17. </intent-filter>
18. </activity>
19. <activity android:name=".NotificationView"
20. android:label="@string/notification_activity"
21. android:parentActivityName=".MainActivity">
22. <meta-data
23. android:name="android.support.PARENT_ACTIVITY"
24. android:value=".MainActivity"/>
25. </activity>
26. </application>
27.
28. </manifest>

Output:
Android - Audio Manager
You can easily control your ringer volume and ringer profile i-e:(silent,vibrate,loud e.t.c)
in android. Android provides AudioManager class that provides access to these
controls.
In order to use AndroidManager class, you have to first create an object of
AudioManager class by calling the getSystemService() method. Its syntax is given
below.
private AudioManager myAudioManager;
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
Once you instantiate the object of AudioManager class, you can
use setRingerMode method to set the audio or ringer profile of your device. Its syntax
is given below.
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
The method setRingerMode takes an integer number as a parameter. For each mode ,
an integer number is assigned that will differentiate between different modes. The
possible modes are.

Sr.No Mode & Description

1
RINGER_MODE_VIBRATE
This Mode sets the device at vibrate mode.

2
RINGER_MODE_NORMAL
This Mode sets the device at normal(loud) mode.

3
RINGER_MODE_SILENT
This Mode sets the device at silent mode.

Once you have set the mode , you can call the getRingerMode() method to get the set
state of the system. Its syntax is given below.
int mod = myAudioManager.getRingerMode();
Apart from the getRingerMode method, there are other methods available in the
AudioManager class to control the volume and other modes. They are listed below.

Sr.No Method & description

1
adjustVolume(int direction, int flags)
This method adjusts the volume of the most relevant stream

2
getMode()
This method returns the current audio mode

3
getStreamMaxVolume(int streamType)
This method returns the maximum volume index for a particular stream

4
getStreamVolume(int streamType)
This method returns the current volume index for a particular stream

5
isMusicActive()
This method checks whether any music is active.

6
startBluetoothSco()
This method Start bluetooth SCO audio connection

7
stopBluetoothSco()
This method stop bluetooth SCO audio connection.

Example
The below example demonstrates the use of AudioManager class. It creates a
application that allows you to set different ringer modes for your device.
To experiment with this example , you need to run this on an actual device.

Steps Description

1 You will use Android studio IDE to create an Android application under a package
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add AudioManager code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 Modify res/values/string.xml file and add necessary string components.

5 Modify AndroidManifest.xml to add necessary permissions.

6 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/MainActivity.java


package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


Button mode,ring,vibrate,silent;
private AudioManager myAudioManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

vibrate=(Button)findViewById(R.id.button3);
ring=(Button)findViewById(R.id.button2);

mode=(Button)findViewById(R.id.button);
silent=(Button)findViewById(R.id.button4);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

vibrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(MainActivity.this,"Now in Vibrate Mode",
Toast.LENGTH_LONG).show();
}
});

ring.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(MainActivity.this,"Now in Ringing Mode",
Toast.LENGTH_LONG).show();
}
});

silent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(MainActivity.this,"Now in silent Mode",
Toast.LENGTH_LONG).show();
}
});

mode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int mod=myAudioManager.getRingerMode();
if(mod==AudioManager.RINGER_MODE_VIBRATE){
Toast.makeText(MainActivity.this,"Now in Vibrate Mode",
Toast.LENGTH_LONG).show();
} else if(mod==AudioManager.RINGER_MODE_NORMAL){
Toast.makeText(MainActivity.this,"Now in Ringing Mode",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Now in Vibrate Mode",
Toast.LENGTH_LONG).show();
}
}
});
}
}
Here is the content of activity_main.xml
Here abc indicates the logo of tutorialspoint

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Audio Recording"
android:id="@+id/textView"
android:textSize="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mode"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="59dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ring"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="vibrate"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Silent"
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />
</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.sairamkrishna.myapplication"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android
Mobile device with your computer. To run the app from Android Studio, open one of
your project's activity files and click Run icon from the tool bar. Android studio will
display Images
Now select silent button, you would get silent icon at Notification bar

Now just select the ring button and then press the current mode button to see that if its status
has been set.
Now press the Vibrate button and then press the current mode button to see that if it is set or
not.It will display the following screen.
Android Bluetooth Tutorial
Bluetooth is a way to exchange data with other devices wirelessly. Android provides
Bluetooth API to perform several tasks such as:

o scan bluetooth devices


o connect and transfer data from and to other devices
o manage multiple connections etc.

Android Bluetooth API


The android.bluetooth package provides a lot of interfaces classes to work with
bluetooth such as:

o BluetoothAdapter
o BluetoothDevice
o BluetoothSocket
o BluetoothServerSocket
o BluetoothClass
o BluetoothProfile
o BluetoothProfile.ServiceListener
o BluetoothHeadset
o BluetoothA2dp
o BluetoothHealth
o BluetoothHealthCallback
o BluetoothHealthAppConfiguration

android-preferences-example
BluetoothAdapter class
By the help of BluetoothAdapter class, we can perform fundamental tasks such as
initiate device discovery, query a list of paired (bonded) devices, create a
BluetoothServerSocket instance to listen for connection requests etc.

Constants of BluetoothAdapter class

BluetoothAdapter class provides many constants. Some of them are as follows:

o String ACTION_REQUEST_ENABLE
o String ACTION_REQUEST_DISCOVERABLE
o String ACTION_DISCOVERY_STARTED
o String ACTION_DISCOVERY_FINISHED

Methods of BluetoothAdapter class

Commonly used methods of BluetoothAdapter class are as follows:

o static synchronized BluetoothAdapter getDefaultAdapter() returns the instance of


BluetoothAdapter.
o boolean enable() enables the bluetooth adapter if it is disabled.
o boolean isEnabled() returns true if the bluetooth adapter is enabled.
o boolean disable() disables the bluetooth adapter if it is enabled.
o String getName() returns the name of the bluetooth adapter.
o boolean setName(String name) changes the bluetooth name.
o int getState() returns the current state of the local bluetooth adapter.
o Set<BluetoothDevice> getBondedDevices() returns a set of paired (bonded)
BluetoothDevice objects.
o boolean startDiscovery() starts the discovery process.
Android Bluetooth Example: enable, disable and make
discovrable bluetooth programmatically

You need to write few lines of code only, to enable or disable the bluetooth.

activity_main.xml

Drag one textview and three buttons from the pallete, now the activity_main.xml file will
like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView android:text=""
8. android:id="@+id/out"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content">
11. </TextView>
12. <Button
13. android:id="@+id/button1"
14. android:layout_width="wrap_content"
15. android:layout_height="wrap_content"
16. android:layout_alignParentLeft="true"
17. android:layout_alignParentTop="true"
18. android:layout_marginLeft="30dp"
19. android:layout_marginTop="49dp"
20. android:text="TURN_ON" />
21.
22. <Button
23. android:id="@+id/button2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_alignLeft="@+id/button1"
27. android:layout_below="@+id/button1"
28. android:layout_marginTop="27dp"
29. android:text="DISCOVERABLE" />
30.
31. <Button
32. android:id="@+id/button3"
33. android:layout_width="wrap_content"
34. android:layout_height="wrap_content"
35. android:layout_alignLeft="@+id/button2"
36. android:layout_below="@+id/button2"
37. android:layout_marginTop="28dp"
38. android:text="TURN_OFF" />
39.
40. </RelativeLayout>

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.BLUETOOTH" />


2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

The full code of AndroidManifest.xml file is given below.

File: AndroidManifest.xml

1. <?xml version="1.0" encoding="utf-8"?>


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.example.bluetooth"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="16" />
10.
11. <uses-permission android:name="android.permission.BLUETOOTH" />
12. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
13.
14. <application
15. android:allowBackup="true"
16. android:icon="@drawable/ic_launcher"
17. android:label="@string/app_name"
18. android:theme="@style/AppTheme" >
19. <activity
20. android:name="com.example.bluetooth.MainActivity"
21. android:label="@string/app_name" >
22. <intent-filter>
23. <action android:name="android.intent.action.MAIN" />
24.
25. <category android:name="android.intent.category.LAUNCHER" />
26. </intent-filter>
27. </activity>
28. </application>
29.
30. </manifest>

Activity class

Let's write the code to enable, disable and make bluetooth discoverable.

File: MainActivity.java

1. package com.example.bluetooth;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.app.Activity;
6. import android.bluetooth.BluetoothAdapter;
7. import android.content.Context;
8. import android.content.Intent;
9. import android.os.Bundle;
10. import android.util.Log;
11. import android.view.View;
12. import android.widget.Button;
13. import android.widget.TextView;
14. import android.widget.Toast;
15.
16. public class MainActivity extends Activity {
17. private static final int REQUEST_ENABLE_BT = 0;
18. private static final int REQUEST_DISCOVERABLE_BT = 0;
19. @Override
20. protected void onCreate(Bundle savedInstanceState) {
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.activity_main);
23. final TextView out=(TextView)findViewById(R.id.out);
24. final Button button1 = (Button) findViewById(R.id.button1);
25. final Button button2 = (Button) findViewById(R.id.button2);
26. final Button button3 = (Button) findViewById(R.id.button3);
27. final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
28. if (mBluetoothAdapter == null) {
29. out.append("device not supported");
30. }
31. button1.setOnClickListener(new View.OnClickListener() {
32. public void onClick(View v) {
33. if (!mBluetoothAdapter.isEnabled()) {
34. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
35. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
36. }
37. }
38. });
39. button2.setOnClickListener(new View.OnClickListener() {
40. @Override
41. public void onClick(View arg0) {
42. if (!mBluetoothAdapter.isDiscovering()) {
43. //out.append("MAKING YOUR DEVICE DISCOVERABLE");
44. Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERABLE",
45. Toast.LENGTH_LONG);
46.
47. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERAB
LE);
48. startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
49.
50. }
51. }
52. });
53. button3.setOnClickListener(new View.OnClickListener() {
54. @Override
55. public void onClick(View arg0) {
56. mBluetoothAdapter.disable();
57. //out.append("TURN_OFF BLUETOOTH");
58. Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGTH_L
ONG);
59.
60. }
61. });
62. }
63.
64. @Override
65. public boolean onCreateOptionsMenu(Menu menu) {
66. // Inflate the menu; this adds items to the action bar if it is present.
67. getMenuInflater().inflate(R.menu.activity_main, menu);
68. return true;
69. }
70.
71. }
Android - Camera
These are the following two ways, in which you can use camera in your application
 Using existing android camera application in our application
 Directly using Camera API provided by android in our application

Using existing android camera application in our application


You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera
application installed on your phone. Its syntax is given below
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Apart from the above, there are other available Intents provided by MediaStore. They
are listed as follows

Sr.No Intent type and description

1 ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured

2 ACTION_VIDEO_CAPTURE
It calls the existing video application in android to capture video

3 EXTRA_SCREEN_ORIENTATION
It is used to set the orientation of the screen to vertical or landscape

4 EXTRA_FULL_SCREEN
It is used to control the user interface of the ViewImage

5 INTENT_ACTION_VIDEO_CAMERA
This intent is used to launch the camera in the video mode

6 EXTRA_SIZE_LIMIT
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult() to launch this activity and wait for
its result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity.
There are methods defined in the activity class that does the same job , but used when
you are not calling from the activity but from somewhere else. They are listed below

Sr.No Activity function description

1 startActivityForResult(Intent intent, int requestCode, Bundle options)


It starts an activity , but can take extra bundle of options with it

2 startActivityFromChild(Activity child, Intent intent, int requestCode)


It launch the activity when your activity is child of any other activity

startActivityFromChild(Activity child, Intent intent, int requestCode,


3 Bundle options)
It work same as above , but it can take extra values in the shape of bundle with
it

startActivityFromFragment(Fragment fragment, Intent intent, int


4 requestCode)
It launches activity from the fragment you are currently inside

startActivityFromFragment(Fragment fragment, Intent intent, int


5 requestCode, Bundle options)
It not only launches the activity from the fragment , but can take extra values
with it

No matter which function you used to launch the activity , they all return the result. The
result can be obtained by overriding the function onActivityResult.

Example
Here is an example that shows how to launch the existing camera application to capture
an image and display the result in the form of bitmap.
To experiment with this example , you need to run this on an actual device on which
camera is supported.

Steps Description

1 You will use Android studio IDE to create an Android application and name it as
Camera under a com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add intent code to launch the Camera.

3 Modify layout XML file res/layout/activity_main.xml

4 Add the Camera permission and run the application and choose a running android
device and install the application on it and verify the results.

Following is the content of the modified main activity file src/MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {


public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100;
public static final String ALLOW_KEY = "ALLOWED";
public static final String CAMERA_PREF = "camera_pref";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {
if (getFromPref(this, ALLOW_KEY)) {
showSettingsAlert();
} else if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)

!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?


if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
showAlert();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
}
} else {
openCamera();
}

}
public static void saveToPreferences(Context context, String key, Boolean allowed) {
SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF,
Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putBoolean(key, allowed);
prefsEditor.commit();
}

public static Boolean getFromPref(Context context, String key) {


SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF,
Context.MODE_PRIVATE);
return (myPrefs.getBoolean(key, false));
}

private void showAlert() {


AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ALLOW",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {


dialog.dismiss();
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
});
alertDialog.show();
}

private void showSettingsAlert() {


AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");

alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW",


new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {


dialog.dismiss();
//finish();
}
});

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "SETTINGS",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {


dialog.dismiss();
startInstalledAppDetailsActivity(MainActivity.this);
}
});

alertDialog.show();
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CAMERA: {
for (int i = 0, len = permissions.length; i < len; i++) {
String permission = permissions[i];

if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
boolean
showRationale =
ActivityCompat.shouldShowRequestPermissionRationale(
this, permission);

if (showRationale) {
showAlert();
} else if (!showRationale) {
// user denied flagging NEVER ASK AGAIN
// you can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting
saveToPreferences(MainActivity.this, ALLOW_KEY, true);
}
}
}
}

// other 'case' lines to check for other


// permissions this app might request
}
}

@Override
protected void onResume() {
super.onResume();
}

public static void startInstalledAppDetailsActivity(final Activity context) {


if (context == null) {
return;
}

final Intent i = new Intent();


i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}

private void openCamera() {


Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
Following will be the content of res/layout/activity_main.xml file−
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
</RelativeLayout>
Following will be the content of res/values/strings.xml to define one new constants
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android
Mobile device with your computer. To run the app from android studio, open one of your
project's activity files and click Run icon from the tool bar. Before starting your
application, Android studio will display following window to select an option where you
want to run your Android application.

Select your mobile device as an option and then check your mobile device which will open the
camera and display following screen –
Android Sensor Tutorial
Sensors can be used to monitor the three-dimensional device movement or change in
the environment of the device.

Android provides sensor api to work with different types of sensors.


Types of Sensors
Android supports three types of sensors:

1) Motion Sensors

These are used to measure acceleration forces and rotational forces along with three
axes.

2) Position Sensors

These are used to measure the physical position of device.

3) Environmental Sensors

These are used to measure the environmental changes such as temperature, humidity
etc.
Android Sensor API
Android sensor api provides many classes and interface. The important classes and
interfaces of sensor api are as follows:

1) SensorManager class

The android.hardware.SensorManager class provides methods :

o to get sensor instance,


o to access and list sensors,
o to register and unregister sensor listeners etc.

You can get the instance of SensorManager by calling the method getSystemService()
and passing the SENSOR_SERVICE constant in it.

1. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);

2) Sensor class

The android.hardware.Sensor class provides methods to get information of the sensor


such as sensor name, sensor type, sensor resolution, sensor type etc.

3) SensorEvent class

Its instance is created by the system. It provides information about the sensor.

4) SensorEventListener interface

It provides two call back methods to get information when sensor values (x,y and z)
change or sensor accuracy changes.

Public and abstract methods Description

void onAccuracyChanged(Sensor sensor, int accuracy) it is called when sensor accuracy is changed.

void onSensorChanged(SensorEvent event) it is called when sensor values are changed.


Android simple sensor app example

Let's see the two sensor examples.

1. A sensor example that prints x, y and z axis values. Here, we are going to see that.
2. A sensor example that changes the background color when device is shuffled. Click
for changing background color of activity sensor example

activity_main.xml

There is only one textview in this file.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="92dp"
14. android:layout_marginTop="114dp"
15. android:text="TextView" />
16.
17. </RelativeLayout>

Activity class

Let's write the code that prints values of x axis, y axis and z axis.
File: MainActivity.java

1. package com.example.sensorsimple;
2. import android.app.Activity;
3. import android.os.Bundle;
4. import android.widget.TextView;
5. import android.widget.Toast;
6. import android.hardware.SensorManager;
7. import android.hardware.SensorEventListener;
8. import android.hardware.SensorEvent;
9. import android.hardware.Sensor;
10. import java.util.List;
11. public class MainActivity extends Activity {
12. SensorManager sm = null;
13. TextView textView1 = null;
14. List list;
15.
16. SensorEventListener sel = new SensorEventListener(){
17. public void onAccuracyChanged(Sensor sensor, int accuracy) {}
18. public void onSensorChanged(SensorEvent event) {
19. float[] values = event.values;
20. textView1.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
21. }
22. };
23.
24. @Override
25. public void onCreate(Bundle savedInstanceState) {
26. super.onCreate(savedInstanceState);
27. setContentView(R.layout.activity_main);
28.
29. /* Get a SensorManager instance */
30. sm = (SensorManager)getSystemService(SENSOR_SERVICE);
31.
32. textView1 = (TextView)findViewById(R.id.textView1);
33.
34. list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
35. if(list.size()>0){
36. sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELAY_NORMAL);
37. }else{
38. Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_LONG).sho
w();
39. }
40. }
41.
42. @Override
43. protected void onStop() {
44. if(list.size()>0){
45. sm.unregisterListener(sel);
46. }
47. super.onStop();
48. }
49. }

Output:
Android - Sending SMS
In Android, you can use SmsManager API or devices Built-in SMS application to send SMS's. In
this tutorial, we shows you two basic examples to send SMS message –

SmsManager API
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
Built-in SMS application
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Of course, both need SEND_SMS permission.
<uses-permission android:name="android.permission.SEND_SMS" />

Apart from the above method, there are few other important functions available in
SmsManager class. These methods are listed below −

Sr.No. Method & Description

1
ArrayList<String> divideMessage(String text)
This method divides a message text into several fragments, none bigger than
the maximum SMS message size.

2
static SmsManager getDefault()
This method is used to get the default instance of the SmsManager

3
void sendDataMessage(String destinationAddress, String scAddress,
short destinationPort, byte[] data, PendingIntent sentIntent,
PendingIntent deliveryIntent)
This method is used to send a data based SMS to a specific application port.

4
void sendMultipartTextMessage(String destinationAddress, String
scAddress, ArrayList<String> parts, ArrayList<PendingIntent>
sentIntents, ArrayList<PendingIntent> deliveryIntents)
Send a multi-part text based SMS.

5
void sendTextMessage(String destinationAddress, String scAddress,
String text, PendingIntent sentIntent, PendingIntent deliveryIntent)
Send a text based SMS.

Example
Following example shows you in practical how to use SmsManager object to send an
SMS to the given mobile number.
To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.

Step Description

1 You will use Android Studio IDE to create an Android application and name it
as tutorialspoint under a package com.example.tutorialspoint.

2 Modify src/MainActivity.java file and add required code to take care of sending sms.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. I'm adding a simple GUI to take mobile number and SMS text to be sent
and a simple button to send SMS.

4 No need to define default string constants at res/values/strings.xml. Android studio


takes care of default constants.

5 Modify AndroidManifest.xml as shown below

6 Run the application to launch Android emulator and verify the result of the changes
done in the application.

Following is the content of the modified main activity


file src/com.example.tutorialspoint/MainActivity.java.
package com.example.tutorialspoint;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;

import android.util.Log;
import android.view.Menu;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
String phoneNo;
String message;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

sendBtn = (Button) findViewById(R.id.btnSendSMS);


txtphoneNo = (EditText) findViewById(R.id.editText);
txtMessage = (EditText) findViewById(R.id.editText2);

sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}

protected void sendSMSMessage() {


phoneNo = txtphoneNo.getText().toString();
message = txtMessage.getText().toString();

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults)
{
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}

}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sending SMS Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Phone Number"
android:phoneNumber="true"
android:textColorHint="@color/abc_primary_text_material_dark"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:textColorHint="@color/abc_primary_text_material_dark"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton"
android:hint="Enter SMS" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Sms"
android:id="@+id/btnSendSMS"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">tutorialspoint</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint" >

<uses-permission android:name="android.permission.SEND_SMS" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
Let's try to run your tutorialspoint application. I assume you have connected your
actual Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar. Before
starting your application, Android studio installer will display following window to select
an option where you want to run your Android application.

Now you can enter a desired mobile number and a text message to be sent on that
number. Finally click on Send SMS button to send your SMS. Make sure your
GSM/CDMA connection is working fine to deliver your SMS to its recipient.
You can take a number of SMS separated by comma and then inside your program you
will have to parse them into an array string and finally you can use a loop to send
message to all the given numbers. That's how you can write your own SMS client. Next
section will show you how to use existing SMS client to send SMS.

Using Built-in Intent to send SMS


You can use Android Intent to send SMS by calling built-in SMS functionality of the
Android. Following section explains different parts of our Intent object required to send
an SMS.

Intent Object - Action to send SMS


You will use ACTION_VIEW action to launch an SMS client installed on your Android
device. Following is simple syntax to create an intent with ACTION_VIEW action.
Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Intent Object - Data/Type to send SMS


To send an SMS you need to specify smsto: as URI using setData() method and data
type will be to vnd.android-dir/mms-sms using setType() method as follows −
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object - Extra to send SMS


Android has built-in support to add phone number and text message to send an SMS as
follows −
smsIntent.putExtra("address" , new String("0123456789;3393993300"));
smsIntent.putExtra("sms_body" , "Test SMS to Angilla");
Here address and sms_body are case sensitive and should be specified in small characters
only. You can specify more than one number in single string but separated by semi-colon
(;).

Example
Following example shows you in practical how to use Intent object to launch SMS client
to send an SMS to the given recipients.
To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.

Step Description

1 You will use Android studio IDE to create an Android application and name it
as tutorialspoint under a package com.example.tutorialspoint.

2 Modify src/MainActivity.java file and add required code to take care of sending SMS.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. I'm adding a simple button to launch SMS Client.

4 No need to define default constants.Android studio takes care of default constants.

5 Modify AndroidManifest.xml as shown below


6 Run the application to launch Android emulator and verify the result of the changes
done in the application.

Following is the content of the modified main activity


file src/com.example.tutorialspoint/MainActivity.java.
package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button startBtn = (Button) findViewById(R.id.button);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMS();
}
});
}

protected void sendSMS() {


Log.i("Send SMS", "");
Intent smsIntent = new Intent(Intent.ACTION_VIEW);

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" , new String ("01234"));
smsIntent.putExtra("sms_body" , "Test ");

try {
startActivity(smsIntent);
finish();
Log.i("Finished sending SMS...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag and Drop Example"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point "
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:textColor="#ff14be3c" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_marginTop="48dp"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Compose SMS"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="54dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">tutorialspoint</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>
Let's try to run your tutorialspoint application. I assume you have connected your
actual Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar. Before
starting your application, Android studio will display following window to select an option
where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which will
display following screen −
Now use Compose SMS button to launch Android built-in SMS clients which is shown below –
You can modify either of the given default fields and finally use send SMS button to send your
SMS to the mentioned recipient.
Android - Phone Calls
Android provides Built-in applications for phone calls, in some occasions we may need
to make a phone call through our application. This could easily be done by using implicit
Intent with appropriate actions. Also, we can use PhoneStateListener and
TelephonyManager classes, in order to monitor the changes in some telephony states
on the device.
This chapter lists down all the simple steps to create an application which can be used
to make a Phone Call. You can use Android Intent to make phone call by calling built-in
Phone Call functionality of the Android. Following section explains different parts of our
Intent object required to make a call.

Intent Object - Action to make Phone Call


You will use ACTION_CALL action to trigger built-in phone call functionality available in
Android device. Following is simple syntax to create an intent with ACTION_CALL
action
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will have
option to modify hardcoded phone number before making a call instead of making a
direct call.

Intent Object - Data/Type to make Phone Call


To make a phone call at a given number 91-000-000-0000, you need to specify tel: as
URI using setData() method as follows −
phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));
The interesting point is that, to make a phone call, you do not need to specify any extra
data or data type.

Example
Following example shows you in practical how to use Android Intent to make phone call
to the given mobile number.
To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.

Step Description

1 You will use Android studio IDE to create an Android application and name it as My
Application under a package com.example.saira_000.myapplication.
2 Modify src/MainActivity.java file and add required code to take care of making a call.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. I'm adding a simple button to Call 91-000-000-0000 number

4 No need to define default string constants.Android studio takes care of default


constants.

5 Modify AndroidManifest.xml as shown below

6 Run the application to launch Android emulator and verify the result of the changes
done in the application.

Following is the content of the modified main activity file src/MainActivity.java.


package com.example.saira_000.myapplication;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonCall);

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0377778888"));

if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
});

}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
android:id="@+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call 0377778888" />

</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >

<uses-permission android:name="android.permission.CALL_PHONE" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.saira_000.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
Let's try to run your My Application application. I assume you have connected your
actual Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.Select your
mobile device as an option and then check your mobile device which will display
following screen −
Now use Call button to make phone call as shown below –
Publishing Android Application
Android application publishing is a process that makes your Android applications
available to users. Infect, publishing is the last phase of the Android application
development process.
Android development life cycle
Once you developed and fully tested your Android Application, you can start selling or
distributing free using Google Play (A famous Android marketplace). You can also
release your applications by sending them directly to users or by letting users download
them from your own website.
You can check a detailed publishing process at Android official website, but this tutorial
will take you through simple steps to launch your application on Google Play. Here is a
simplified check list which will help you in launching your Android application −

Step Activity

1 Regression Testing Before you publish your application, you need to make sure
that its meeting the basic quality expectations for all Android apps, on all of the
devices that you are targeting. So perform all the required testing on different
devices including phone and tablets.

2 Application Rating When you will publish your application at Google Play, you will
have to specify a content rating for your app, which informs Google Play users of its
maturity level. Currently available ratings are (a) Everyone (b) Low maturity (c)
Medium maturity (d) High maturity.
3 Targeted Regions Google Play lets you control what countries and territories where
your application will be sold. Accordingly you must take care of setting up time zone,
localization or any other specific requirement as per the targeted region.

4 Application Size Currently, the maximum size for an APK published on Google Play
is 50 MB. If your app exceeds that size, or if you want to offer a secondary
download, you can use APK Expansion Files, which Google Play will host for free on
its server infrastructure and automatically handle the download to devices.

5 SDK and Screen Compatibility It is important to make sure that your app is
designed to run properly on the Android platform versions and device screen sizes
that you want to target.

6 Application Pricing Deciding whether you app will be free or paid is important
because, on Google Play, free app's must remain free. If you want to sell your
application then you will have to specify its price in different currencies.

7 Promotional Content It is a good marketing practice to supply a variety of high-


quality graphic assets to showcase your app or brand. After you publish, these
appear on your product details page, in store listings and search results, and
elsewhere.

8 Build and Upload release-ready APK The release-ready APK is what you you will
upload to the Developer Console and distribute to users. You can check complete
detail on how to create a release-ready version of your app: Preparing for Release.

9 Finalize Application Detail Google Play gives you a variety of ways to promote
your app and engage with users on your product details page, from colourful
graphics, screen shots, and videos to localized descriptions, release details, and
links to your other apps. So you can decorate your application page and provide as
much as clear crisp detail you can provide.
Export Android Application Process

Apk development process


Before exporting the apps, you must some of tools
 Dx tools(Dalvik executable tools ): It going to convert .class file to .dex file. it
has useful for memory optimization and reduce the boot-up speed time
 AAPT(Android assistance packaging tool):it has useful to convert .Dex
file to.Apk
 APK(Android packaging kit): The final stage of deployment process is called as
.apk.
You will need to export your application as an APK (Android Package) file before you
upload it Google Play marketplace.
To export an application, just open that application project in Android studio and
select Build → Generate Signed APK from your Android studio and follow the simple
steps to export your application −
Next select, Generate Signed APK option as shown in the above screen shot and then click it
so that you get following screen where you will choose Create new keystore to store your
application.

Enter your key store path,key store password,key alias and key password to protect your
application and click on Next button once again. It will display following screen to let you create
an application –
Once you filled up all the information,like app destination,build type and flavours
click finish button While creating an application it will show as below

Finally, it will generate your Android Application as APK formate File which will be
uploaded at Google Play marketplace.

Google Play Registration


The most important step is to register with Google Play using Google Play Marketplace.
You can use your existing google ID if you have any otherwise you can create a new
Google ID and then register with the marketplace. You will have following screen to
accept terms and condition.
You can use Continue to payment button to proceed to make a payment of $25 as a
registration fee and finally to complete your account detail.
Once you are a registered user at Google Play, you can upload release-ready APK for
your application and finally you will complete application detail using application detail
page as mentioned in step 9 of the above mentioned checklist.

Signing Your App Manually


You do not need Android Studio to sign your app. You can sign your app from the
command line using standard tools from the Android SDK and the JDK. To sign an app
in release mode from the command line −

 Generate a private key using keytool


$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
 Compile your app in release mode to obtain an unsigned APK
 Sign your app with your private key using jarsigner
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1
-keystore my-release-key.keystore my_application.apk alias_name
 Verify that your APK is signed. For example −
$ jarsigner -verify -verbose -certs my_application.apk
 Align the final APK package using zipalign.
$ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk
Kotlin Tutorial
What is Kotlin?
Kotlin is a programming language introduced by JetBrains in 2011, the official designer
of the most intelligent Java IDE, named Intellij IDEA. Kotlin is free, has been free and
will remain free. It is developed under the Apache 2.0 license and the source code is
available on GitHub.
This is a strongly statically typed general-purpose programming language that runs on
JVM. In 2017, Google announced Kotlin is an official language for android development.
Kotlin is an open source programming language that combines object-oriented
programming and functional features into a unique platform. The content is divided into
various chapters that contain related topics with simple and useful examples.
Kotlin is a modern programming language that makes developers happier. Kotlin is easy to
pick up, so you can create powerful applications immediately.

Currently, Kotlin mainly targets the Java Virtual Machine (JVM), but also compiles to
JavaScript. Kotlin is influenced by other popular programming languages such as Java,
C#, JavaScript, Scala and Groovy. The syntax of Kotlin may not be exactly similar to
Java Programming Language, however, internally Kotlin is reliant on the existing Java
Class library to produce wonderful results for the programmers. Kotlin provides
interoperability, code safety, and clarity to the developers around the world.

What is Kotlin?
Kotlin is a new open source programming language like Java, JavaScript, Python etc. It
is a high level strongly statically typed language that combines functional and technical
part in a same place. Currently, Kotlin mainly targets the Java Virtual Machine (JVM),
but also compiles to JavaScript.
Kotlin is influenced by other popular programming languages such as Java, C#,
JavaScript, Scala and Groovy. The syntax of Kotlin may not be exactly similar to Java
Programming Language, however, internally Kotlin is reliant on the existing Java Class
library to produce wonderful results for the programmers. Kotlin provides
interoperability, code safety, and clarity to the developers around the world.
Kotlin was developed and released by JetBrains in 2016. Kotlin is free, has been free
and will remain free. It is developed under the Apache 2.0 license and the source code
is available on GitHub

Why Kotlin?
Kotlin is getting high popularity among all level of programmers and it is used for:

 Cross-platform Mobile applications.


 Android Application Development.
 Web Application Development
 Server Side Applications
 Desktop Application Development
 Data science based applications

Kotlin works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) and it's
100% compatible with Java.
Kotlin is used by many large companies like Google, Netflix, Slack, Uber etc to develop
their Android based applications.
The most importantly, there are many companies actively looking for Kotlin developers,
especially in the Android development space.

Kotlin Version?
At the time of writing this tutorial on Aug 3, 2021, The current Kotlin released version is
1.5.21

Kotlin Advantages
Following are some of the advantages of using Kotlin for your application development.
1. Easy Language − Kotlin supports object-oriented and functional constructs and very
easy to learn. The syntax is pretty much similar to Java, hence for any Java
programmer it is very easy to remember any Kotlin Syntax.
2. Very Concise − Kotlin is based on Java Virtual Machine (JVM) and it is a functional
language. Thus, it reduce lots of boiler plate code used in other programming
languages.
3. Runtime and Performance − Kotlin gives a better performance and small runtime for
any application.
4. Interoperability − Kotlin is mature enough to build an interoperable application in a
less complex manner.
5. Brand New − Kotlin is a brand new language that gives developers a fresh start. It is
not a replacement of Java, though it is developed over JVM. Kotlin has been accepted
as the first official language of Android Application Development. Kotlin can also be
defined as - Kotlin = Java + Extra updated new features.

Kotlin Drawbacks
Following are some of the disadvantages of using Kotlin.
1. Namespace declaration − Kotlin allows developers to declare the functions at the
top level. However, whenever the same function is declared in many places of your
application, then it is hard to understand which function is being called.
2. No Static Declaration − Kotlin does not have usual static handling modifier like Java,
which can cause some problem to the conventional Java developer.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy