Unit 3 Cyber Laws

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Unit-9.

Telephony APIs
9.1 Working with Telephony Utilities, Using SMS, Making and Receiving
Phone Calls, Notifying a User, Notifying with Status Bar,
9.2 Vibrating the Phone, Blinking the Lights, Making Noise, Customizing the
Notification, Designing Useful Notification.

APIs-Application Programming Interface


Telephony APIs
The telephony API is used to among other things monitor phone information
including the current states of the phone, connections, network etc. In this example, we
want to utilize the telephone manager part of the Application Framework and use phone
listeners (PhoneStateListener) to retrieve various phone states.

Android Telephony framework provides us the functionalities of the mobile. It gives


us information about functionalities like calls, SMS, MMS, network, data services, IMEI
number, and so on.

For better understanding, you can consider Dialer, Browser, Sim App toolkit, Broadcast
receivers, and so on.

Android Telephony and Telephony Manager

Android Telephony is a package provided by Android to operate and get information


about the network interfaces and device details. It has several interfaces and classes that are
used to provide various functionalities.

Android Telephony Manager is one such class that is present in the


android.telephony package. It provides you with several methods to get the network or
telephony information and know its current state. Along with this, you also get the subscriber
information using the Telephony Manager methods.

To access the Telephony Manager in your programming, you can simply import the
android.telphony.TelephonyManager class.

After that, you need to use the getSystemService() to create the TelephonyManager
object, and then you can use it to get system information.

Android TelephonyManager

The android.telephony.TelephonyManager class provides information about the telephony


services such as subscriber id, sim serial number, phone network type etc. Moreover, you can
determine the phone state etc.

val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as


TelephonyManager
Architecture of Android Telephony
The architecture of Android Telephony is subdivided into four layers. These four layers
help it interact with users and low-level devices like your network adapters.
The four layers involved in the Android Telephony are described below:
1. Communication Processor
The communication processor is used to communicate and collect data from various
peripherals. It usually takes input and processes and distributes it among the communication
network.
2. Radio Interface Layer (RIL)
The Radio Interface Layer is an interface through which the hardware components
interact with the frameworks. It’s a bridge with protocols for the Telephony services and is
therefore known as protocol stack for Telephone. The RIL consist of two components that are
as follows:
a. RIL Daemon –
RIL Daemon starts up immediately when your device starts. The RIL Daemon reads
system properties and makes the libraries ready that are required by Vendor RIL.
b. Vendor RIL –
Vendor RIL is a library that is specific to each network modem.
3. Framework Services
Framework services consist of various packages and assists the Telephony Manager
in directing all the application API requests to RIL. The framework services start
immediately when the device boots up.
4. Application
Applications are the last layer of the Telephony architecture. The applications are
used directly by the user to interact with the Telephony Services. Some of the standard
applications are IMEI checker, Dialer, SIM Toolkit, Browser, etc.

Example

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.telephonyutilites"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.TelephonyUtilites"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<service android:name=".MyService"
android:enabled="true"
android:exported="true"/>
</application>

</manifest>

Activitymain.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="150dp"
android:fontFamily="adamina"
android:text="Mobile Details:"
android:textSize="20dp" />

</RelativeLayout>

ActivityMain.java

package com.example.telephonyutilites;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.textView);
//instance of TelephonyManager
TelephonyManager tele_man = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
String nwcountryISO = tele_man.getNetworkCountryIso();
String SIMCountryISO = tele_man.getSimCountryIso();

String PhoneType = ""; // it'll hold the type of phone i.e CDMA / GSM/ None
int phoneType = tele_man.getPhoneType();
switch (phoneType) {
case (TelephonyManager.PHONE_TYPE_CDMA):
PhoneType = "CDMA";
break;
case (TelephonyManager.PHONE_TYPE_GSM):
PhoneType = "GSM";
break;
case (TelephonyManager.PHONE_TYPE_NONE):
PhoneType = "NONE";
break;
}
// true or false for roaming or not
boolean checkRoaming = tele_man.isNetworkRoaming();
String data = "Your Mobile Details are enlisted below: \n";
data += "\n Network Country ISO is - " + nwcountryISO;
data += "\n SIM Country ISO is - " + SIMCountryISO;
data += "\n Network type is - " + PhoneType;
data += "\n Roaming on is - " + checkRoaming;

//Now we'll display the information


tv.setText(data);//displaying the information in the textView
}
}
Using SMS
SMSManager class manages operations like sending a text message, data message, and
multimedia messages (MMS). For sending a text message method sendTextMessage() is used
likewise for multimedia message sendMultimediaMessage() and for data message
sendDataMessage() method is used. The details of each function are:

Function Description
sendTextMessage(String destinationAddress,
sendTextMessage() String scAddress, String text, PendingIntent sentIntent,
PendingIntent deliveryIntent, long messageId)
sendDataMessage(String destinationAddress,
sendDataMessage() String scAddress, short destinationPort, byte[] data,
PendingIntent sentIntent, PendingIntent deliveryIntent)
sendMultimediaMessage(Context context,
sendMultimediaMessage() Uri contentUri, String locationUrl,
Bundle configOverrides, PendingIntent sentIntent

You can create a 2 emulator and Send SMS,Receive SMS 1st emulator to 2nd emulator
calling no-5554 and 5556

Note:-Set the permission in emulator->setting->apps & Notifications->Click


sendSms(applicationname)->click permission->allow.

Activitymain.xml

package com.example.sendsms;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText phonenumber,message;
Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send=findViewById(R.id.button);
phonenumber=findViewById(R.id.editText);
message=findViewById(R.id.editText2);
send.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {


String number=phonenumber.getText().toString();
String msg=message.getText().toString();
try {
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(number,null,msg,null,null);
Toast.makeText(getApplicationContext(),"Message
Sent",Toast.LENGTH_LONG).show();
}catch (Exception e)
{
Toast.makeText(getApplicationContext(),"Some fiedls is
Empty",Toast.LENGTH_LONG).show();
}
}
});
}
}
Androidmanifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.sendsms">
<uses-permission android:name="android.permission.SEND_SMS"/>
<dist:module dist:instant="true" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.SendSMS"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

</manifest>
Mainactivity,java

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter number"
android:inputType="textPersonName" />

<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter message"
android:inputType="textPersonName" />

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="60dp"
android:layout_marginRight="60dp"
android:text="SEND" />

</LinearLayout>

Making and Receiving 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.

You can create a 2 emulator and calling 1st emulator to 2nd emulator calling no-5554
and 5556.

Note:-Set the permission in emulator->setting->apps & Notifications->Click


sendSms(applicationname)->click permission->allow.

Example
MainActivity.java
package com.example.callingapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


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

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phone_number = edittext.getText().toString();
callIntent.setData(Uri.parse("tel:" + phone_number));

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

activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:hint="Enter Number"
android:layout_marginTop="98dp" />

<Button
android:id="@+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="164dp"
android:layout_marginBottom="505dp"
android:text="Call " />

</RelativeLayout>

Activitymanifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.callingapp"
android:versionCode="1"
android:versionName="1.0">

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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.CallingApp"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Notifying a User, Notifying with Status Bar


A Notification is a message you can display to the user outside of your application's
normal UI. When you tell the system to issue a notification, it first appears as an icon in the
notification area.
To see the details of the notification, the user opens the notification drawer. Both the
notification area and the notification drawer are system-controlled areas that the user can
view at any time.

Activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ANDROID NOTIFICATION"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.091"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_marginBottom="112dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Notify"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Activitymain.java

package com.example.notification;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.NotificationChannel;
import android.os.Build;
import android.os.Bundle;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel("My Notification","My
Notification",NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}

private void addNotification() {


NotificationCompat.Builder builder =
new NotificationCompat.Builder(MainActivity.this,"My Notification")
.setSmallIcon(R.drawable.ic_launcher_background) //set icon for notification
.setContentTitle("Display Notification Tittle") //set title of notification
.setContentText("This is a notification message,also display
Notification")//this is notification message
.setAutoCancel(true) // makes auto cancel of notification
.setPriority(NotificationCompat.PRIORITY_DEFAULT); //set priority of
notification

// Add as notification
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
Vibrating the Phone
In android, using vibrate service, we can vibrate android mobile. This example
demonstrate about how to make an Android device vibrate

Mainactivity.java

package com.example.vibratingphone;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


int view = R.layout.activity_main;
Button textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout parent = findViewById(R.id.parent);
textView = findViewById(R.id.text);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(500,
VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(500);
}
}
});
}
}
androidmanifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.vibratingphone">

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


<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.VibratingPhone"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/parent"
android:gravity="center"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/text"
android:textSize="18sp"
android:text="Click here to vibrate"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

Blinking the Lights


All the beginners who are into the android development world should build a simple
android application that can turn on/off the flashlight or torchlight by clicking a Button. So at
the end of this article, one will be able to build their own android flashlight application with a
simple layout.

Activitymain.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:text="Flashlight"
android:textSize="50sp"
android:textStyle="bold|italic" />

<!--This is the simple divider between above


TextView and ToggleButton-->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginStart="32dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:background="@android:color/darker_gray" />

<!--This toggle button by default toggles


between the ON and OFF we no need to
set separate TextView for it-->
<ToggleButton
android:id="@+id/toggle_flashlight"
android:layout_width="200dp"
android:layout_height="75dp"
android:layout_gravity="center"
android:layout_marginTop="32dp"
android:onClick="toggleFlashLight"
android:textSize="25sp" />

</LinearLayout>

MainActivity.java

package com.example.flashlight;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.annotation.RequiresApi;
public class MainActivity extends AppCompatActivity {
private ToggleButton toggleFlashLightOnOff;
private CameraManager cameraManager;
private String getCameraID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleFlashLightOnOff = findViewById(R.id.toggle_flashlight);
cameraManager = (CameraManager)
getSystemService(Context.CAMERA_SERVICE);
try {
getCameraID = cameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
public void toggleFlashLight(View view) {
if (toggleFlashLightOnOff.isChecked()) {
try {

cameraManager.setTorchMode(getCameraID, true);
Toast.makeText(MainActivity.this, "Flashlight is turned ON",
Toast.LENGTH_SHORT).show();
} catch (CameraAccessException e) {

e.printStackTrace();
}
} else {
try {
cameraManager.setTorchMode(getCameraID, false);
Toast.makeText(MainActivity.this, "Flashlight is turned OFF",
Toast.LENGTH_SHORT).show();
} catch (CameraAccessException e) {

e.printStackTrace();
}
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void finish() {
super.finish();
try {
cameraManager.setTorchMode(getCameraID, false);
Toast.makeText(MainActivity.this, "Flashlight is turned OFF",
Toast.LENGTH_SHORT).show();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
Androidmanifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.flashlight">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.flash" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.FlashLight"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>
Making Noise

1.First Add a button in Android Studio.


2.Go to MainActivity.java. text and give an id to the button
3.Now add the media player.
4.Go to res > New > Android resource directory
5.Now you can find raw under the res category.
6.Add a sample.mp3 file under raw.
7.Add the setOnclicklistener, so that when the button is pressed you will hear the sound.
8.Go to the live device view. On pressing the button, you will hear a long sound.

Example

Activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:text="Audio Controller" />

<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:text="start" />

<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="pause" />

</RelativeLayout>

MainActivity.java

package com.example.mediaplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


Button start,pause;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);

//creating media player


final MediaPlayer mp= MediaPlayer.create(MainActivity.this, R.raw.kesariya);

start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});

}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.mediaplayer">

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MediaPlayer"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

You might also like