Java Programs
Java Programs
BCA Semester – 6
Journal
H & H Kotak Institute of Science, Rajkot
BCA Department
H & H B Kotak Institute of Science, Rajkot
BCA Department
Laboratory Certificate
Mobile Application Development in Android using Kotlin during the academic year
Date: _____________
Introduction to Kotlin
Programming
Unit-1 Introduction to Kotlin Programing
1. Hello World Program
1 /*Hello World Program*/
2
3 fun main() {
4 println("Hello World")
5 print("Hello ")
6 print("World")
7 }
2. Mutable variable
1 //Mutable Variable in Kotlin
2 fun main() {
3 var name = "Java Programing"
4 println("Name = $name")
5
6 name = "Kotlin Progaming"
7 println("Name = $name")
8 }
4. Use of Array
1 //Array data type in kotlin
2
3 fun main(args: Array<String>) {
4 val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
5 println("Value at 3rd position : " + numbers[2])
6 }
5. Arithmatic Operators
1 //Arithmatic Operators in Kotlin
2
3 fun main() {
4 var a: Int=10
5 var b: Int=20
6 println("a+b= " + (a+b))
Page 5 of 48
CS-31 Mobile Application Development in Android using Kotlin
7 println("a-b= " + (a-b))
8 println("a*b= " + (a*b))
9 println("a/b= " + (a/b))
10 println("a%b= " + (a%b))
11 }
6. UDF
1 //Kotlin UDF.
2 fun main(args: Array<String>) {
3 printHello()
4 }
5
6 fun printHello(){
7 println("Hello, World!")
8 }
8. Function recursion
1 //Function recursion in Kotlin
2
3 fun main(args: Array<String>) {
4 val a = 4
5
6 val result = factorial(a)
7 println( result )
8 }
9
10 fun factorial(a:Int):Int{
11 val result:Int
12
13 if( a <= 1){
14 result = a
15 }else{
16 result = a*factorial(a-1)
17 }
18 return result
19 }
Unit-1 Introduction to Kotlin Programing
9. Range in Kotlin
1 //when loop with range.
2
3 fun main(args: Array<String>) {
4 val day = 2
5 when (day) {
6 in 1..5 -> println("Weekday")
7 else -> println("Weekend")
8 }
9 }
17. Constructor
1 //Constructor in Kotlin
2
3 class Person{
4 // Member Variables
5 var name: String
6 var age: Int
7
8 // Initializer Block
9 init {
10 println("Initializer Block")
11 }
12
13 // Secondary Constructor
14 constructor ( _name: String, _age: Int) {
15 this.name = _name
Unit-1 Introduction to Kotlin Programing
16 this.age = _age
17 println("Name = $name")
18 println("Age = $age")
19 }
20 }
21
22 fun main(args: Array<String>) {
23 val zara = Person("Malay Dave", 40)
24 }
18. Inheritance
1 //Inheritance in Kotlin
2
3 open class ABC {
4 open fun think () {
5 print("Hey!! i am thinking ")
6 }
7 }
8 class BCD: ABC() { // inheritance happens using default
9 constructor
10 override fun think() {
11 print("I Am from Child")
12 }
13 }
14 fun main(args: Array<String>) {
15 var a = BCD()
16 a.think()
17 }
Page 17 of 48
CS-31 Mobile Application Development in Android using Kotlin
29 android:textSize="20sp"
30 app:layout_constraintStart_toEndOf="@+id/textView"
31 app:layout_constraintTop_toTopOf="parent" />
32
33 <TextView
34 android:id="@+id/textView2"
35 android:layout_width="98dp"
36 android:layout_height="34dp"
37 android:layout_marginStart="36dp"
38 android:layout_marginTop="64dp"
39 android:text="Your text:"
40 android:textSize="20sp"
41 app:layout_constraintStart_toStartOf="parent"
42 app:layout_constraintTop_toBottomOf="@+id/textView" />
43 <EditText
44 android:id="@+id/editTextTextPersonName2"
45 android:layout_width="wrap_content"
46 android:layout_height="wrap_content"
47 android:layout_marginStart="24dp"
48 android:layout_marginTop="60dp"
49 android:ems="10"
50 android:inputType="textPersonName"
51 android:textSize="20sp"
52 app:layout_constraintStart_toEndOf="@+id/textView2"
53 app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName" />
54 <Button
55 android:id="@+id/button"
56 android:layout_width="wrap_content"
57 android:layout_height="wrap_content"
58 android:layout_marginTop="312dp"
59 android:text="Display Text"
60 app:layout_constraintEnd_toEndOf="parent"
61 app:layout_constraintHorizontal_bias="0.46"
62 app:layout_constraintStart_toStartOf="parent"
63 app:layout_constraintTop_toTopOf="parent" />
64 </androidx.constraintlayout.widget.ConstraintLayout>
65 ----------------------------------------------------------------
66 MainActivity.kt
----------------
package com.example.edittext2
1 import androidx.appcompat.app.AppCompatActivity
2 import android.os.Bundle
3 import android.widget.Button
4 import android.widget.EditText
5 import android.widget.Toast
6
7 class MainActivity : AppCompatActivity() {
8 override fun onCreate(savedInstanceState: Bundle?) {
9 super.onCreate(savedInstanceState)
10 setContentView(R.layout.activity_main)
11 val text1 = findViewById<EditText>(R.id.editTextTextPersonName)
12 val text2 = findViewById<EditText>(R.id.editTextTextPersonName2)
13 val but1=findViewById<Button>(R.id.button)
14
15 but1.setOnClickListener {
16 text2.setText(text1.text.toString())
17
18 Toast.makeText(applicationContext,text1.text.toString(),Toast.LENGTH_LONG).show()
19 }
20 }
21 }
Unit-3 Android User Interface Design
Page 25 of 48
CS-31 Mobile Application Development in Android using Kotlin
5 import android.content.Intent;
6 import android.os.Bundle;
7 import android.view.View;
8 import android.widget.Button;
9
10 public class MainActivity extends AppCompatActivity {
11
12 Button but1;
13
14 @Override
15 protected void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 setContentView(R.layout.activity_main);
18
19 process();
20 }
21 void process() {
22 but1=(Button) findViewById(R.id.button);
23
24 but1.setOnClickListener(new View.OnClickListener() {
25 @Override
26 public void onClick(View view) {
27 Intent i = new Intent(getApplicationContext(),
MainActivity2.class);
28 i.putExtra("Value1", "Intent Example");
29 i.putExtra("Value2", "By Dr. Malay Dave");
30 startActivity(i);
31 }
32 });
33
34 }
35 }
----------------------------------------------------------------
1 MainActivity2.kt
2 ----------------
3 package com.example.intentdemo;
4
5 import androidx.appcompat.app.AppCompatActivity;
6
7 import android.content.Intent;
8 import android.os.Bundle;
9 import android.view.View;
10 import android.widget.Button;
11 import android.widget.Toast;
12
13 public class MainActivity2 extends AppCompatActivity {
14
15 Button but2;
16
17 @Override
18 protected void onCreate(Bundle savedInstanceState) {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.activity_main2);
21
22 Bundle extras = getIntent().getExtras();
23 String value1 = extras.getString("Value1");
String value2 = extras.getString("Value2");
24 Toast.makeText(getApplicationContext(), "Values are:\n First value: " +
25 value1 + "\n Second Value: " + value2, Toast.LENGTH_LONG).show();
26
27 process();
28 }
29
Unit-3 Android User Interface Design
30 void process() {
31 but2=(Button) findViewById(R.id.button2);
32 but2.setOnClickListener(new View.OnClickListener() {
33 @Override
public void onClick(View view) {
34 Intent i = new Intent(getApplicationContext(),
35 MainActivity.class);
36 startActivity(i);
37 }
38 });
}
}
Page 33 of 48
CS-31 Mobile Application Development in Android using Kotlin
30 }
31
32 override fun onCreate(savedInstanceState: Bundle?) {
33 super.onCreate(savedInstanceState)
34 setContentView(R.layout.activity_main)
35 val fileName = findViewById(R.id.editTextFile) as EditText
36 val fileData = findViewById(R.id.editTextData) as EditText
37 val saveButton = findViewById<Button>(R.id.button_save) as Button
38 val viewButton = findViewById(R.id.button_view) as Button
39
40 saveButton.setOnClickListener(View.OnClickListener {
41 myExternalFile = File(getExternalFilesDir(filepath),
fileName.text.toString())
42 try {
43 val fileOutPutStream = FileOutputStream(myExternalFile)
44 fileOutPutStream.write(fileData.text.toString().toByteArray())
45 fileOutPutStream.close()
46 } catch (e: IOException) {
47 e.printStackTrace()
48 }
49 Toast.makeText(applicationContext,"data save",Toast.LENGTH_SHORT).show()
50 })
51 viewButton.setOnClickListener(View.OnClickListener {
52 myExternalFile = File(getExternalFilesDir(filepath),
fileName.text.toString())
53
54 val filename = fileName.text.toString()
55 myExternalFile = File(getExternalFilesDir(filepath),filename)
56 if(filename.toString()!=null && filename.toString().trim()!=""){
57 var fileInputStream =FileInputStream(myExternalFile)
58 var inputStreamReader: InputStreamReader =
InputStreamReader(fileInputStream)
59 val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)
60 val stringBuilder: StringBuilder = StringBuilder()
61 var text: String? = null
62 while ({ text = bufferedReader.readLine(); text }() != null) {
63 stringBuilder.append(text)
64 }
65 fileInputStream.close()
66 //Displaying data on EditText
67
Toast.makeText(applicationContext,stringBuilder.toString(),Toast.LENGTH_SHORT).show()
68 }
69 })
70
71 if (!isExternalStorageAvailable || isExternalStorageReadOnly) {
72 saveButton.isEnabled = false
73 }
74 }
75 }
---------------------------------------------------------------------------------
AndroidManifest.xml
1 ---------------------
2 <?xml version="1.0" encoding="utf-8"?>
3 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
4 package="example.javatpoint.com.kotlinexternalstoragereadwrite">
5 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
6 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
7 <application
8 android:allowBackup="true"
9 android:icon="@mipmap/ic_launcher"
10 android:label="@string/app_name"
11 android:roundIcon="@mipmap/ic_launcher_round"
12 android:supportsRtl="true"
Unit-4 Data Base Connectivity and Content Provider
13 android:theme="@style/AppTheme">
14 <activity android:name=".MainActivity">
15 <intent-filter>
16 <action android:name="android.intent.action.MAIN" />
17
18 <category android:name="android.intent.category.LAUNCHER" />
19 </intent-filter>
20 </activity>
21 </application>
22
</manifest>
32. SharedPreferences
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <android.support.constraint.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context="example.com.kotlinsharedpreference.MainActivity">
9
10 <TableLayout
11 android:layout_width="368dp"
12 android:layout_height="495dp"
13 android:layout_marginBottom="8dp"
14 android:layout_marginEnd="8dp"
15 android:layout_marginStart="8dp"
16 android:layout_marginTop="8dp"
Page 35 of 48
CS-31 Mobile Application Development in Android using Kotlin
17 app:layout_constraintBottom_toBottomOf="parent"
18 app:layout_constraintEnd_toEndOf="parent"
19 app:layout_constraintStart_toStartOf="parent"
20 app:layout_constraintTop_toTopOf="parent">
21 <TableRow>
22 <TextView
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:layout_column="0"
26 android:layout_marginLeft="10sp"
27 android:layout_marginStart="10sp"
28 android:text="Enter Id"
29 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
30 <EditText
31 android:id="@+id/editId"
32 android:layout_width="201dp"
33 android:layout_height="wrap_content"
34 android:layout_column="1"
35 android:layout_marginLeft="50sp"
36 android:layout_marginStart="50sp"
37 android:hint="id"
38 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
39 </TableRow>
40 <TableRow>
41
42 <TextView
43 android:layout_width="wrap_content"
44 android:layout_height="wrap_content"
45 android:layout_column="0"
46 android:layout_marginLeft="10sp"
47 android:layout_marginStart="10sp"
48 android:text="Enter Name"
49 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
50
51 <EditText
52 android:id="@+id/editName"
53 android:layout_width="wrap_content"
54 android:layout_height="wrap_content"
55 android:layout_column="1"
56 android:layout_marginLeft="50sp"
57 android:layout_marginStart="50sp"
58 android:hint="name"
59 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
60 </TableRow>
61 <TableRow android:layout_marginTop="60dp">
62
63 <TextView
64 android:layout_width="wrap_content"
65 android:layout_height="wrap_content"
66 android:layout_column="0"
67 android:layout_marginLeft="10sp"
68 android:layout_marginStart="10sp"
69 android:text="Your Id"
70 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
71 <TextView
72 android:id="@+id/textViewShowId"
73 android:layout_width="wrap_content"
74 android:layout_height="wrap_content"
75 android:layout_column="1"
Unit-4 Data Base Connectivity and Content Provider
76 android:layout_marginLeft="50sp"
77 android:layout_marginStart="50sp"
78 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
79 />
</TableRow>
80 <TableRow android:layout_marginTop="20dp">
81 <TextView
82 android:layout_width="wrap_content"
83 android:layout_height="wrap_content"
84 android:layout_column="0"
85 android:layout_marginLeft="10sp"
86 android:layout_marginStart="10sp"
87 android:text="Your Name"
88 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
89 <TextView
90 android:id="@+id/textViewShowName"
91 android:layout_width="wrap_content"
92 android:layout_height="wrap_content"
93 android:layout_column="1"
94 android:layout_marginLeft="50sp"
95 android:layout_marginStart="50sp"
96 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
97 />
98 </TableRow>
99 </TableLayout>
100
101 <LinearLayout
102 android:layout_width="fill_parent"
103 android:layout_height="wrap_content"
104 android:layout_marginBottom="16dp"
105 android:layout_marginEnd="8dp"
106 android:layout_marginStart="8dp"
107 android:orientation="horizontal"
108 android:gravity="center"
109 app:layout_constraintBottom_toBottomOf="parent"
110 app:layout_constraintEnd_toEndOf="parent"
111 app:layout_constraintHorizontal_bias="0.0"
112 app:layout_constraintStart_toStartOf="parent">
113 <Button
114 android:id="@+id/save"
115 android:layout_width="wrap_content"
116 android:layout_height="wrap_content"
117 android:text="Save" />
118 <Button
119 android:id="@+id/view"
120 android:layout_width="wrap_content"
121 android:layout_height="wrap_content"
122 android:text="View" />
123 <Button
124 android:id="@+id/clear"
125 android:layout_width="wrap_content"
126 android:layout_height="wrap_content"
127 android:text="Clear" />
128 </LinearLayout>
129 </android.support.constraint.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package example.com.kotlinsharedpreference
2
3 import android.content.Context
4 import android.content.SharedPreferences
Page 37 of 48
CS-31 Mobile Application Development in Android using Kotlin
5 import android.support.v7.app.AppCompatActivity
6 import android.os.Bundle
7 import android.view.View
8 import android.widget.Button
9 import android.widget.EditText
10 import android.widget.TextView
11
12
13
14 class MainActivity : AppCompatActivity() {
15
16 private val sharedPrefFile = "kotlinsharedpreference"
17
18 override fun onCreate(savedInstanceState: Bundle?) {
19 super.onCreate(savedInstanceState)
20 setContentView(R.layout.activity_main)
21
22 val inputId = findViewById<EditText>(R.id.editId)
23 val inputName = findViewById<EditText>(R.id.editName)
24 val outputId = findViewById<TextView>(R.id.textViewShowId)
25 val outputName = findViewById<TextView>(R.id.textViewShowName)
26
27 val btnSave = findViewById<Button>(R.id.save)
28 val btnView = findViewById<Button>(R.id.view)
29 val btnClear = findViewById<Button>(R.id.clear)
30 val sharedPreferences: SharedPreferences =
31 this.getSharedPreferences(sharedPrefFile,Context.MODE_PRIVATE)
32 btnSave.setOnClickListener(View.OnClickListener {
33 val id:Int = Integer.parseInt(inputId.text.toString())
34 val name:String = inputName.text.toString()
35 val editor:SharedPreferences.Editor = sharedPreferences.edit()
36 editor.putInt("id_key",id)
37 editor.putString("name_key",name)
38 editor.apply()
39 editor.commit()
40 })
41 btnView.setOnClickListener {
42 val sharedIdValue = sharedPreferences.getInt("id_key",0)
43 val sharedNameValue =
44 sharedPreferences.getString("name_key","defaultname")
45 if(sharedIdValue.equals(0) && sharedNameValue.equals("defaultname")){
46 outputName.setText("default name: ${sharedNameValue}").toString()
48 outputId.setText("default id: ${sharedIdValue.toString()}")
49 }else{
50 outputName.setText(sharedNameValue).toString()
51 outputId.setText(sharedIdValue.toString())
52 }
53
54 }
55 btnClear.setOnClickListener(View.OnClickListener {
56 val editor = sharedPreferences.edit()
57 editor.clear()
58 editor.apply()
59 outputName.setText("").toString()
60 outputId.setText("".toString())
61 })
62 }
63 }
Unit-4 Data Base Connectivity and Content Provider
Page 39 of 48
CS-31 Mobile Application Development in Android using Kotlin
33 // Writing Contacts to log
34 Log.d("Name: ", log);
35 }
36
37 }
38 }
---------------------------------------------------------------------------
DatabaseHandler.java
---------------------
1 package com.example.sqlitedemojava;
2
3 import android.content.ContentValues;
4 import android.content.Context;
5 import android.database.Cursor;
6 import android.database.sqlite.SQLiteDatabase;
7 import android.database.sqlite.SQLiteOpenHelper;
8 import java.util.ArrayList;
9 import java.util.List;
10
11 public class DatabaseHandler extends SQLiteOpenHelper {
12 private static final int DATABASE_VERSION = 1;
13 private static final String DATABASE_NAME = "contactsManager";
14 private static final String TABLE_CONTACTS = "contacts";
15 private static final String KEY_ID = "id";
16 private static final String KEY_NAME = "name";
17 private static final String KEY_PH_NO = "phone_number";
18
19 public DatabaseHandler(Context context) {
20 super(context, DATABASE_NAME, null, DATABASE_VERSION);
21 //3rd argument to be passed is CursorFactory instance
22 }
23 // Creating Tables
24 @Override
25 public void onCreate(SQLiteDatabase db) {
26 String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
27 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
28 + KEY_PH_NO + " TEXT" + ")";
29 db.execSQL(CREATE_CONTACTS_TABLE);
30 }
31 // Upgrading database
32 @Override
33 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
34 // Drop older table if existed
35 db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
36
37 // Create tables again
38 onCreate(db);
39 }
40 // code to add the new contact
41 void addContact(Contact contact) {
42 SQLiteDatabase db = this.getWritableDatabase();
43
44 ContentValues values = new ContentValues();
45 values.put(KEY_NAME, contact.getName()); // Contact Name
46 values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
47 // Inserting Row
48 db.insert(TABLE_CONTACTS, null, values);
49 //2nd argument is String containing nullColumnHack
50 db.close(); // Closing database connection
51 }
52 // code to get the single contact
53 Contact getContact(int id) {
54 SQLiteDatabase db = this.getReadableDatabase();
55
Unit-4 Data Base Connectivity and Content Provider
56 Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
57 KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
58 new String[] { String.valueOf(id) }, null, null, null, null);
59 if (cursor != null)
60 cursor.moveToFirst();
61
62 Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
63 cursor.getString(1), cursor.getString(2));
64 // return contact
65 return contact;
66 }
67 // code to get all contacts in a list view
68 public List<Contact> getAllContacts() {
69 List<Contact> contactList = new ArrayList<Contact>();
70 // Select All Query
71 String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
72
73 SQLiteDatabase db = this.getWritableDatabase();
74 Cursor cursor = db.rawQuery(selectQuery, null);
75
76 // looping through all rows and adding to list
77 if (cursor.moveToFirst()) {
78 do {
79 Contact contact = new Contact();
80 contact.setID(Integer.parseInt(cursor.getString(0)));
81 contact.setName(cursor.getString(1));
82 contact.setPhoneNumber(cursor.getString(2));
83 // Adding contact to list
84 contactList.add(contact);
85 } while (cursor.moveToNext());
86 }
87 // return contact list
88 return contactList;
89 }
90 // code to update the single contact
91 public int updateContact(Contact contact) {
92 SQLiteDatabase db = this.getWritableDatabase();
93
94 ContentValues values = new ContentValues();
95 values.put(KEY_NAME, contact.getName());
96 values.put(KEY_PH_NO, contact.getPhoneNumber());
97
98 // updating row
99 return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
100 new String[] { String.valueOf(contact.getID()) });
101 }
102 // Deleting single contact
103 public void deleteContact(Contact contact) {
104 SQLiteDatabase db = this.getWritableDatabase();
105 db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
106 new String[] { String.valueOf(contact.getID()) });
107 db.close();
108 }
109 // Getting contacts Count
110 public int getContactsCount() {
112 String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
113 SQLiteDatabase db = this.getReadableDatabase();
114 Cursor cursor = db.rawQuery(countQuery, null);
115 cursor.close();
116 // return count
117 return cursor.getCount();
118 }
119 }
Page 41 of 48
CS-31 Mobile Application Development in Android using Kotlin
----------------------------------------------------------------------------
Contact.java
------------
1 package com.example.sqlitedemojava;
2
3 public class Contact {
4 int _id;
5 String _name;
6 String _phone_number;
7 public Contact(){ }
8 public Contact(int id, String name, String _phone_number){
9 this._id = id;
10 this._name = name;
11 this._phone_number = _phone_number;
12 }
13 public Contact(String name, String _phone_number){
14 this._name = name;
15 this._phone_number = _phone_number;
16 }
17 public int getID(){
18 return this._id;
19 }
20 public void setID(int id){
21 this._id = id;
22 }
23 public String getName(){
24 return this._name;
25 }
26 public void setName(String name){
27 this._name = name;
28 }
29 public String getPhoneNumber(){
30 return this._phone_number;
31 }
32 public void setPhoneNumber(String phone_number){
33 this._phone_number = phone_number;
34 }
35 }
Unit-5 Common Android API
Unit – 5
Page 43 of 48
CS-31 Mobile Application Development in Android using Kotlin
34. Android device vibrate programmatically
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
11 xmlns:tools="http://schemas.android.com/tools"
12 android:layout_width="match_parent"
13 android:layout_height="match_parent"
14 tools:context=".MainActivity">
15 <TextView
16 android:layout_width="wrap_content"
17 android:layout_height="wrap_content"
18 android:layout_centerHorizontal="true"
19 android:layout_marginTop="70dp"
20 android:background="#008080"
21 android:padding="5dp"
22 android:text="Vibrate Device"
23 android:textColor="#fff"
24 android:textSize="24sp"
25 android:textStyle="bold" />
26 <TextView
27 android:id="@+id/textView"
28 android:layout_width="wrap_content"
29 android:layout_height="wrap_content"
30 android:layout_centerInParent="true"
31 android:textColor="@android:color/holo_blue_dark"
32 android:textSize="24sp"
33 android:textStyle="bold" />
34 </RelativeLayout>
35
36 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.vibratedevicekotlin
2
3 import android.content.Context
4 import android.os.Build
5 import androidx.appcompat.app.AppCompatActivity
6 import android.os.Bundle
7 import android.os.VibrationEffect
8 import android.os.Vibrator
9
10 @Suppress("DEPRECATION")
11 class MainActivity : AppCompatActivity() {
12 override fun onCreate(savedInstanceState: Bundle?) {
13 super.onCreate(savedInstanceState)
14 setContentView(R.layout.activity_main)
15
16 title = "KotlinApp"
17 val v = (getSystemService(Context.VIBRATOR_SERVICE) as Vibrator)
18 // Vibrate for 500 milliseconds
19 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
20
21 v.vibrate(VibrationEffect.createOneShot(500,VibrationEffect.DEFAULT_AMPLITUDE))
Unit-5 Common Android API
22 }
23 else {
24 v.vibrate(500)
25 }
26 }
27 }
---------------------------------------------------------------------------
AndroidManifest.xml
---------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:tools="http://schemas.android.com/tools">
4
5 <uses-permission android:name="android.permission.VIBRATE" />
6 <application
7 android:allowBackup="true"
8 android:dataExtractionRules="@xml/data_extraction_rules"
9 android:fullBackupContent="@xml/backup_rules"
10 android:icon="@mipmap/ic_launcher"
11 android:label="@string/app_name"
12 android:roundIcon="@mipmap/ic_launcher_round"
13 android:supportsRtl="true"
14 android:theme="@style/Theme.VibrateDeviceKotlin"
15 tools:targetApi="31">
16 <activity
17 android:name=".MainActivity"
18 android:exported="true">
19 <intent-filter>
20 <action android:name="android.intent.action.MAIN" />
21 <category android:name="android.intent.category.LAUNCHER" />
22 </intent-filter>
23 <meta-data
24 android:name="android.app.lib_name"
25 android:value="" />
26 </activity>
27 </application>
28 </manifest>
Page 45 of 48
CS-31 Mobile Application Development in Android using Kotlin
35. Android telephony api
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 android:paddingBottom="@dimen/activity_vertical_margin"
6 android:paddingLeft="@dimen/activity_horizontal_margin"
7 android:paddingRight="@dimen/activity_horizontal_margin"
8 android:paddingTop="@dimen/activity_vertical_margin"
9 tools:context=".MainActivity" >
10
11 <TextView
12 android:id="@+id/textView1"
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:layout_alignParentLeft="true"
16 android:layout_alignParentTop="true"
17 android:layout_marginLeft="38dp"
18 android:layout_marginTop="30dp"
19 android:text="Phone Details:" />
20
21 </RelativeLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.telephonyapi
2
3 import android.os.Bundle;
4 import android.app.Activity;
5 import android.content.Context;
6 import android.telephony.TelephonyManager;
7 import android.view.Menu;
8 import android.widget.TextView;
9
10 public class MainActivity extends Activity {
11 TextView textView1;
12 @Override
13 protected void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.activity_main);
16
17 textView1=(TextView)findViewById(R.id.textView1);
18
19 //Get the instance of TelephonyManager
20 TelephonyManager
tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
21
22 //Calling the methods of TelephonyManager the returns the information
23 String IMEINumber=tm.getDeviceId();
24 String subscriberID=tm.getDeviceId();
25 String SIMSerialNumber=tm.getSimSerialNumber();
26 String networkCountryISO=tm.getNetworkCountryIso();
27 String SIMCountryISO=tm.getSimCountryIso();
28 String softwareVersion=tm.getDeviceSoftwareVersion();
29 String voiceMailNumber=tm.getVoiceMailNumber();
30
31 //Get the phone type
32 String strphoneType="";
33
34 int phoneType=tm.getPhoneType();
35
Unit-5 Common Android API
36 switch (phoneType)
37 {
38 case (TelephonyManager.PHONE_TYPE_CDMA):
39 strphoneType="CDMA";
40 break;
41 case (TelephonyManager.PHONE_TYPE_GSM):
42 strphoneType="GSM";
43 break;
44 case (TelephonyManager.PHONE_TYPE_NONE):
45 strphoneType="NONE";
46 break;
47 }
48
49 //getting information if phone is in roaming
50 boolean isRoaming=tm.isNetworkRoaming();
51
52 String info="Phone Details:\n";
53 info+="\n IMEI Number:"+IMEINumber;
54 info+="\n SubscriberID:"+subscriberID;
55 info+="\n Sim Serial Number:"+SIMSerialNumber;
56 info+="\n Network Country ISO:"+networkCountryISO;
57 info+="\n SIM Country ISO:"+SIMCountryISO;
58 info+="\n Software Version:"+softwareVersion;
59 info+="\n Voice Mail Number:"+voiceMailNumber;
60 info+="\n Phone Network Type:"+strphoneType;
61 info+="\n In Roaming? :"+isRoaming;
62
63 textView1.setText(info);//displaying the information in the textView
64 }
65 }
---------------------------------------------------------------------------
AndroidManifest.xml
---------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3 package="com.javatpoint.telephonymanager"
4 android:versionCode="1"
5 android:versionName="1.0" >
6
7 <uses-sdk
8 android:minSdkVersion="8"
9 android:targetSdkVersion="17" />
10
11 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
12
13 <application
14 android:allowBackup="true"
15 android:icon="@drawable/ic_launcher"
16 android:label="@string/app_name"
17 android:theme="@style/AppTheme" >
18 <activity
19 android:name="com.javatpoint.telephonymanager.MainActivity"
20 android:label="@string/app_name" >
21 <intent-filter>
22 <action android:name="android.intent.action.MAIN" />
23
24 <category android:name="android.intent.category.LAUNCHER" />
25 </intent-filter>
26 </activity>
27 </application>
28 </manifest>
Page 47 of 48
CS-31 Mobile Application Development in Android using Kotlin