0% found this document useful (0 votes)
10 views19 pages

PR 24

The document contains code snippets for three Android applications: a Bluetooth manager, a SQLite database manager, and a login page. Each application includes XML layout files and corresponding Java code to implement functionality such as enabling Bluetooth, inserting data into a database, and validating user login credentials. The examples demonstrate the use of various Android components like Buttons, EditTexts, and ListViews.

Uploaded by

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

PR 24

The document contains code snippets for three Android applications: a Bluetooth manager, a SQLite database manager, and a login page. Each application includes XML layout files and corresponding Java code to implement functionality such as enabling Bluetooth, inserting data into a database, and validating user login credentials. The examples demonstrate the use of various Android components like Buttons, EditTexts, and ListViews.

Uploaded by

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

Pr.

24
1. Write a program to turn on, get visible, list devices and turnoff Bluetooth with the help of
following GUI.
<?xml version="1.0" encoding="utf-8"?> btnListDevices =
<LinearLayout findViewById(R.id.btnListDevices);
xmlns:android="http://schemas.android.com/apk/res/and btnDisableBluetooth =
roid" findViewById(R.id.btnDisableBluetooth);
android:layout_width="match_parent" listViewDevices =
android:layout_height="match_parent" findViewById(R.id.listViewDevices
android:orientation="vertical" btnListDevices.setOnClickListener(view -
android:gravity="center" >{
android:padding="16dp"> if (bluetoothAdapter != null &&
bluetoothAdapter.isEnabled()) {
<Button
android:id="@+id/btnEnableBluetooth" Set<BluetoothDevice>
android:layout_width="wrap_content" pairedDevices =
android:layout_height="wrap_content" bluetoothAdapter.getBondedDevices();
android:text="Turn On Bluetooth" /> ArrayList<String> deviceList =
new ArrayList<>();
<Button for (BluetoothDevice device :
android:id="@+id/btnDiscoverable" pairedDevices)
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Make Discoverable" deviceList.add(device.getName() + " - " +
android:layout_marginTop="10dp" /> device.getAddress());

<Button listViewDevices.setAdapter(new
android:id="@+id/btnListDevices" ArrayAdapter<>(this,
android:layout_width="wrap_content" android.R.layout.simple_list_item_1,
android:layout_height="wrap_content" deviceList));
android:text="List Paired Devices"
} else showToast("Turn on
android:layout_marginTop="10dp" />
Bluetooth first");
<ListView });
android:id="@+id/listViewDevices"
android:layout_width="match_parent"
android:layout_height="200dp" btnDisableBluetooth.setOnClickListener(
android:layout_marginTop="10dp"/> view -> {
if (bluetoothAdapter != null &&
<Button
bluetoothAdapter.isEnabled()) {
android:id="@+id/btnDisableBluetooth"
android:layout_width="wrap_content" bluetoothAdapter.disable();
android:layout_height="wrap_content" showToast("Bluetooth turned
android:text="Turn Off Bluetooth" OFF");
android:layout_marginTop="10dp" /> } else showToast("Bluetooth is
already OFF");
</LinearLayout> });
Java code: }
package com.example.bluetoothmanager;

import android.bluetooth.BluetoothAdapter; private void showToast(String message)


import android.bluetooth.BluetoothDevice; {
import android.content.Intent; Toast.makeText(this, message,
import androidx.appcompat.app.AppCompatActivity; Toast.LENGTH_SHORT).show();
import java.util.ArrayList; }
import java.util.Set; }
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
Button btnEnableBluetooth, btnDiscoverable,
btnListDevices, btnDisableBluetooth;
ListView listViewDevices;

@RequiresApi(api = Build.VERSION_CODES.S)
@Override
setContentView(R.layout.activity_main);

bluetoothAdapter =
BluetoothAdapter.getDefaultAdapter();
btnEnableBluetooth =
findViewById(R.id.btnEnableBluetooth);
btnDiscoverable =
findViewById(R.id.btnDiscoverable);
Pr.26
1. Write a program to insert data in SQLite database using AsyncTask
Xml: MainActivity.java
<?xml version="1.0" encoding="utf-8"?> package com.example.databaseexample;
<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" import android.annotation.SuppressLint;
android:id="@+id/main" import android.database.Cursor;
android:layout_width="match_parent" import android.os.Bundle;
android:layout_height="match_parent" import android.view.View;
tools:context=".MainActivity" import android.widget.Button;
android:gravity="center" import android.widget.EditText;
android:orientation="vertical"> import android.widget.TextView;

<TextView import androidx.appcompat.app.AppCompatActivity;


android:layout_width="wrap_content"
android:layout_height="wrap_content" import java.util.ArrayList;
android:text="@string/sqlite_database"
android:textSize="36sp" public class MainActivity extends AppCompatActivity {
app:layout_constraintBottom_toBottomOf="parent" EditText et1, et2, et3;
app:layout_constraintEnd_toEndOf="parent" TextView tv1;
app:layout_constraintStart_toStartOf="parent" DBHelper dbHelper;
app:layout_constraintTop_toTopOf="parent" /> Button b1, b2, b3, b4;

<EditText @SuppressLint("MissingInflatedId")
android:id="@+id/et1" @Override
android:layout_width="match_parent" protected void onCreate(Bundle savedInstanceState) {
android:layout_height="wrap_content" super.onCreate(savedInstanceState);
android:textAlignment="center" setContentView(R.layout.activity_main);
android:hint="Enter roll no:"/>

<EditText et1 = findViewById(R.id.et1);


android:id="@+id/et2" et2 = findViewById(R.id.et2);
android:layout_width="match_parent" et3 = findViewById(R.id.et3);
android:layout_height="wrap_content" b1 = findViewById(R.id.bt1);
android:textAlignment="center" b2 = findViewById(R.id.bt2);
android:hint="@string/name"/> b3 = findViewById(R.id.bt3);
b4 = findViewById(R.id.bt4);
<EditText tv1 = findViewById(R.id.tv1);
android:id="@+id/et3"
android:layout_width="match_parent" dbHelper = new DBHelper(MainActivity.this);
android:layout_height="wrap_content"
android:textAlignment="center"
android:hint="Branch:" /> b1.setOnClickListener(new View.OnClickListener() {
@Override
<LinearLayout public void onClick(View v) {
android:layout_width="match_parent" String t1 = et1.getText().toString();
android:layout_height="wrap_content" String t2 = et2.getText().toString();
android:orientation="horizontal" String t3 = et3.getText().toString();
> dbHelper.insert(t1, t2, t3);
et1.setText("");
<Button et2.setText("");
android:id="@+id/bt1" et3.setText("");
android:layout_width="wrap_content" }
android:layout_height="wrap_content" });
android:layout_gravity="center" // Update data
android:background="#F44336" b2.setOnClickListener(new View.OnClickListener() {
android:padding="20dp" @Override
android:text="add" public void onClick(View v) {
android:textSize="20dp" String t1 = et1.getText().toString();
android:textStyle="bold" String t2 = et2.getText().toString();
android:layout_marginLeft="100dp" String t3 = et3.getText().toString();
/> dbHelper.insert(t1, t2, t3);

<Button }
android:id="@+id/bt2" });
android:layout_width="wrap_content" //Delete Data
android:layout_height="wrap_content" b3.setOnClickListener(new View.OnClickListener() {
android:layout_gravity="center" @Override
android:background="#8A0707" public void onClick(View v) {
android:padding="20dp" String m_rollnumber = et1.getText().toString();
android:text="update"
android:textSize="20dp" dbHelper.deletedata(m_rollnumber);
android:textStyle="bold"
android:layout_marginLeft="60dp" }
/> });

b4.setOnClickListener(new View.OnClickListener() {
</LinearLayout> @Override
public void onClick(View v) {
<LinearLayout display_data();
android:layout_width="match_parent" }
android:layout_height="150dp" });
android:orientation="horizontal" }
>
private void display_data()
<Button {
android:id="@+id/bt3" Cursor cur = dbHelper.getData();
android:layout_width="wrap_content" StringBuilder sb = new StringBuilder();
android:layout_height="wrap_content" while (cur.moveToNext()) {
android:layout_gravity="center" String t1 = cur.getString(0);
android:background="#F44336" String t2 = cur.getString(1);
android:padding="20dp" String t3 = cur.getString(2);
android:text="delete" sb.append("\n Roll no="+t1);
android:textSize="20dp" sb.append("\n Name="+t2);
android:textStyle="bold" sb.append("\n Branch="+t3 +"\n");
android:layout_marginLeft="100dp"
/> }
tv1.setText(sb.toString());
<Button }
android:id="@+id/bt4" }
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#630A0A"
android:padding="20dp"
android:text="display"
android:textSize="20dp"
android:textStyle="bold"
android:layout_marginLeft="60dp"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv1"
android:textSize="20dp"
android:hint="records:"
android:text=""/>

</LinearLayout>
Pr.27
Xml code: Java code:
<?xml version="1.0" encoding="utf-8"?> package com.cscorner.loginpage;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" import androidx.appcompat.app.AppCompatActivity;
xmlns:tools="http://schemas.android.com/tools" import android.os.Bundle;
android:layout_width="match_parent" import android.view.View;
android:layout_height="match_parent" import android.widget.Button;
android:orientation="vertical" import android.widget.EditText;
android:padding="16dp" import android.widget.Toast;
tools:context=".MainActivity">
public class MainActivity extends AppCompatActivity {
<TextView
android:layout_width="wrap_content" private EditText etUsername, etPassword;
android:layout_height="wrap_content" private Button btnLogin;
android:text="Login Form"
android:textSize="24sp" // Updated credentials as requested
android:textStyle="bold" private final String VALID_USERNAME = "Dasmita";
android:layout_gravity="center_horizontal" private final String VALID_PASSWORD = "1234";
android:layout_marginBottom="32dp"/>
@Override
<TextView protected void onCreate(Bundle savedInstanceState) {
android:layout_width="wrap_content" super.onCreate(savedInstanceState);
android:layout_height="wrap_content" setContentView(R.layout.activity_main);
android:text="Username"
android:layout_marginBottom="4dp"/> // Initialize UI components
etUsername = findViewById(R.id.etUsername);
<LinearLayout etPassword = findViewById(R.id.etPassword);
android:layout_width="match_parent" btnLogin = findViewById(R.id.btnLogin);
android:layout_height="wrap_content"
android:minHeight="48dp" // Set click listener for login button
android:background="?attr/selectableItemBackground" btnLogin.setOnClickListener(new View.OnClickListener() {
android:padding="8dp"> @Override
public void onClick(View v) {
<EditText validateLogin();
android:id="@+id/etUsername" }
android:layout_width="match_parent" });
android:layout_height="wrap_content" }
android:hint="Enter username"
android:inputType="text" private void validateLogin() {
android:background="@null"/> // Get user input
</LinearLayout> String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
<TextView
android:layout_width="wrap_content" if (username.isEmpty()) {
android:layout_height="wrap_content" etUsername.setError("Username cannot be empty");
android:text="Password" etUsername.requestFocus();
android:layout_marginTop="16dp" return;
android:layout_marginBottom="4dp"/> }

<LinearLayout if (password.isEmpty()) {
android:layout_width="match_parent" etPassword.setError("Password cannot be empty");
android:layout_height="wrap_content" etPassword.requestFocus();
android:minHeight="48dp" return;
android:background="?attr/selectableItemBackground" }
android:padding="8dp"> if (username.equals(VALID_USERNAME) &&
<EditText password.equals(VALID_PASSWORD)) {
android:id="@+id/etPassword" // Successful login
android:layout_width="match_parent" Toast.makeText(this, "Login successful! Welcome " +
android:layout_height="wrap_content" VALID_USERNAME, Toast.LENGTH_LONG).show();
android:hint="Enter password" // Clear fields after successful login
android:inputType="textPassword" etUsername.setText("");
android:background="@null"/> etPassword.setText("");
</LinearLayout> } else {
<Button // Failed login
android:id="@+id/btnLogin" Toast.makeText(this, "Login failed. Invalid credentials",
android:layout_width="match_parent" Toast.LENGTH_LONG).show();
// Clear just the password field on failure
android:layout_height="wrap_content"
etPassword.setText("");
android:text="Login" etPassword.requestFocus();
android:layout_marginTop="32dp" }
android:minHeight="48dp"/> }
}
</LinearLayout>
Pr.28
Xml code: Java code:
<?xml version="1.0" encoding="utf-8"?> package com.example.loginapp;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/and import androidx.appcompat.app.AppCompatActivity;
roid" import android.os.Bundle;
xmlns:tools="http://schemas.android.com/tools" import android.view.View;
android:layout_width="match_parent" import android.widget.Button;
android:layout_height="match_parent" import android.widget.EditText;
android:orientation="vertical" import android.widget.TextView;
android:padding="24dp" import android.widget.Toast;
tools:context=".MainActivity">
public class MainActivity extends AppCompatActivity {
<TextView
android:layout_width="wrap_content" private EditText etUsername, etPassword;
android:layout_height="wrap_content" private Button btnLogin;
android:text="Login Form" private TextView tvAttempts;
android:textSize="24sp"
android:textStyle="bold" // Valid credentials (in real app, use proper authentication)
android:layout_gravity="center_horizontal" private final String VALID_USERNAME = "admin";
android:layout_marginBottom="32dp"/> private final String VALID_PASSWORD = "password123";

<TextView private int remainingAttempts = 3;


android:layout_width="wrap_content" private final int MAX_ATTEMPTS = 3;
android:layout_height="wrap_content"
android:text="Username" @Override
android:layout_marginBottom="4dp"/> protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<EditText setContentView(R.layout.activity_main);
android:id="@+id/etUsername"
android:layout_width="match_parent" // Initialize views
android:layout_height="56dp" etUsername = findViewById(R.id.etUsername);
android:hint="Enter username (min 4 chars)" etPassword = findViewById(R.id.etPassword);
android:inputType="text" btnLogin = findViewById(R.id.btnLogin);
android:minHeight="48dp"/> tvAttempts = findViewById(R.id.tvAttempts);

<TextView // Set click listener for login button


android:layout_width="wrap_content" btnLogin.setOnClickListener(new View.OnClickListener() {
android:layout_height="wrap_content" @Override
android:text="Password" public void onClick(View v) {
android:layout_marginTop="16dp" validateLogin();
android:layout_marginBottom="4dp"/> }
});
<EditText }
android:id="@+id/etPassword"
android:layout_width="match_parent" private void validateLogin() {
android:layout_height="56dp" // Get user input
android:hint="Enter password (min 6 chars)" String username = etUsername.getText().toString().trim();
android:inputType="textPassword" String password = etPassword.getText().toString().trim();
android:minHeight="48dp"/>
// Validate empty fields
<Button if (username.isEmpty()) {
android:id="@+id/btnLogin" etUsername.setError("Username cannot be empty");
android:layout_width="match_parent" etUsername.requestFocus();
android:layout_height="56dp" return;
android:text="Login" }
android:layout_marginTop="32dp"/>
if (password.isEmpty()) {
<TextView etPassword.setError("Password cannot be empty");
android:id="@+id/tvAttempts" etPassword.requestFocus();
android:layout_width="wrap_content" private void updateAttemptsText() {
android:layout_height="wrap_content" tvAttempts.setText("Remaining attempts: " + remainingAttempts);
android:layout_marginTop="16dp" if (remainingAttempts == 1) {
android:text="Remaining attempts: 3"
android:textColor="@color/red"/> tvAttempts.setTextColor(getResources().getColor(android.R.color.holo_red_
dark));
</LinearLayout> }
}

private void resetLoginAttempts() {


remainingAttempts = MAX_ATTEMPTS;
tvAttempts.setText("Remaining attempts: " + remainingAttempts);
return; private void updateAttemptsText() {
} tvAttempts.setText("Remaining attempts: " + remainingAttempts);
if (remainingAttempts == 1) {
// Check credentials
if (username.equals(VALID_USERNAME) && tvAttempts.setTextColor(getResources().getColor(android.R.color.holo_red_
password.equals(VALID_PASSWORD)) { dark));
// Successful login }
Toast.makeText(this, "Login successful!", }
Toast.LENGTH_LONG).show();
resetLoginAttempts(); private void resetLoginAttempts() {
// Here you would typically start a new activity remainingAttempts = MAX_ATTEMPTS;
} else { tvAttempts.setText("Remaining attempts: " + remainingAttempts);
// Failed login
remainingAttempts--; tvAttempts.setTextColor(getResources().getColor(android.R.color.black));
updateAttemptsText(); }
}
if (remainingAttempts > 0) { tvAttempts.setTextColor(getResources().getColor(android.R.color.black));
Toast.makeText(this, }
"Login failed. " + remainingAttempts + " }
attempts remaining", return;
Toast.LENGTH_LONG).show(); }
} else {
btnLogin.setEnabled(false); // Validate username length (min 4 chars)
Toast.makeText(this, if (username.length() < 4) {
"No more attempts. Please try again later.", etUsername.setError("Username must be at least 4 characters");
Toast.LENGTH_LONG).show(); etUsername.requestFocus();
} return;
}
// Clear password field
etPassword.setText(""); // Validate password length (min 6 chars)
etPassword.requestFocus(); if (password.length() < 6) {
}
}
Pr.30
Xml code: Java code:
<?xml version="1.0" encoding="utf-8"?> package com.cscorner.email;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" import androidx.appcompat.app.AppCompatActivity;
android:layout_width="match_parent" import android.content.Intent;
android:layout_height="match_parent" import android.os.Bundle;
android:orientation="vertical" import android.view.View;
android:padding="16dp"> import android.widget.Button;
import android.widget.EditText;
<!-- Email Address --> import android.widget.Toast;
<TextView
android:layout_width="wrap_content" public class MainActivity extends AppCompatActivity {
android:layout_height="wrap_content"
android:text="To Email Address" private EditText etEmailAddress, etSubject, etMessage;
android:textSize="16sp"/> private Button btnSend;

<EditText @Override
android:id="@+id/etEmailAddress" protected void onCreate(Bundle savedInstanceState) {
android:layout_width="match_parent" super.onCreate(savedInstanceState);
android:layout_height="wrap_content" setContentView(R.layout.activity_main);
android:hint="[email protected]"
android:inputType="textEmailAddress"/> etEmailAddress = findViewById(R.id.etEmailAddress);
etSubject = findViewById(R.id.etSubject);
<!-- Subject --> etMessage = findViewById(R.id.etMessage);
<TextView btnSend = findViewById(R.id.btnSend);
android:layout_width="wrap_content"
android:layout_height="wrap_content" btnSend.setOnClickListener(new View.OnClickListener() {
android:text="Subject" @Override
android:textSize="16sp" public void onClick(View v) {
android:layout_marginTop="16dp"/> sendEmail();
}
<EditText });
android:id="@+id/etSubject" }
android:layout_width="match_parent"
android:layout_height="wrap_content" private void sendEmail() {
android:hint="Email subject"/> String emailAddress =
etEmailAddress.getText().toString().trim();
<!-- Email Content --> String subject = etSubject.getText().toString().trim();
<TextView String message = etMessage.getText().toString().trim();
android:layout_width="wrap_content" if (emailAddress.isEmpty()) {
android:layout_height="wrap_content" etEmailAddress.setError("Email address is required");
android:text="Message" etEmailAddress.requestFocus();
android:textSize="16sp" return;
android:layout_marginTop="16dp"/> }

<EditText if (subject.isEmpty()) {
android:id="@+id/etMessage" etSubject.setError("Subject is required");
android:layout_width="match_parent" etSubject.requestFocus();
android:layout_height="150dp" return;
android:gravity="top" }
android:hint="Type your message here"
android:inputType="textMultiLine"/> if (message.isEmpty()) {
etMessage.setError("Message is required");
<!-- Send Button --> etMessage.requestFocus();
<Button return;
android:id="@+id/btnSend" }
android:layout_width="match_parent" Intent intent = new Intent(Intent.ACTION_SEND);
android:layout_height="wrap_content" intent.setType("message/rfc822");
android:layout_marginTop="16dp" intent.putExtra(Intent.EXTRA_EMAIL, new String[]
android:text="Send Email"/> {emailAddress});
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
</LinearLayout> intent.putExtra(Intent.EXTRA_TEXT, message);

try {
startActivity(Intent.createChooser(intent, "Send email
using..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "No email clients installed.",
Toast.LENGTH_SHORT).show();
}
}
}
Pr.29
Xml code: Java code:
<?xml version="1.0" encoding="utf-8"?> package com.cscorner.smssend;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" import androidx.appcompat.app.AppCompatActivity;
android:layout_width="match_parent" import android.Manifest;
android:layout_height="match_parent" import android.content.BroadcastReceiver;
android:orientation="vertical" import android.content.Context;
android:padding="16dp"> import android.content.Intent;
import android.content.IntentFilter;
<!-- Phone Number Input --> import android.content.pm.PackageManager;
<TextView import androidx.core.content.ContextCompat;
android:layout_width="wrap_content"
android:layout_height="wrap_content" public class MainActivity extends AppCompatActivity {
android:text="Phone Number"
android:textSize="16sp"/> private static final int SMS_PERMISSION_CODE = 100;
private EditText etPhoneNumber, etMessage;
<EditText private Button btnSendSMS;
android:id="@+id/etPhoneNumber" private TextView tvReceivedSMS;
android:layout_width="match_parent"
android:layout_height="wrap_content" @Override
android:hint="Enter phone number" protected void onCreate(Bundle savedInstanceState) {
android:inputType="phone"/> super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<!-- SMS Message Input -->
<TextView // Initialize views
android:layout_width="wrap_content" etPhoneNumber = findViewById(R.id.etPhoneNumber);
android:layout_height="wrap_content" etMessage = findViewById(R.id.etMessage);
android:text="Message" btnSendSMS = findViewById(R.id.btnSendSMS);
android:textSize="16sp" tvReceivedSMS = findViewById(R.id.tvReceivedSMS);
android:layout_marginTop="16dp"/>
// Check and request SMS permissions
<EditText checkSmsPermission();
android:id="@+id/etMessage"
android:layout_width="match_parent" // Set click listener for send button
android:layout_height="150dp" btnSendSMS.setOnClickListener(new
android:gravity="top" View.OnClickListener() {
android:hint="Type your message here" @Override
android:inputType="textMultiLine"/> public void onClick(View v) {
sendSMS();
<!-- Send SMS Button --> }
<Button });
android:id="@+id/btnSendSMS"
android:layout_width="match_parent" // Register receiver for incoming SMS
android:layout_height="wrap_content" IntentFilter filter = new IntentFilter();
android:layout_marginTop="16dp"
android:text="Send SMS"/> filter.addAction("android.provider.Telephony.SMS_RECEIV
ED");
<!-- Received SMS Display --> registerReceiver(smsReceiver, filter);
<TextView }
android:id="@+id/tvReceivedSMS"
android:layout_width="match_parent" private void sendSMS() {
android:layout_height="wrap_content" String phoneNumber =
android:layout_marginTop="24dp" etPhoneNumber.getText().toString().trim();
android:text="Received messages will appear here" String message = etMessage.getText().toString().trim();
android:textSize="16sp"/>
if (phoneNumber.isEmpty()) {
</LinearLayout> Toast.makeText(this, "Please enter phone number",
Toast.LENGTH_SHORT).show();
return;
}

if (message.isEmpty()) {
Toast.makeText(this, "Please enter message",
Toast.LENGTH_SHORT).show();
return;
}

try {
SmsManager smsManager =
SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null,
message, null, null);
e.printStackTrace(); Toast.makeText(this, "SMS sent successfully",
} Toast.LENGTH_SHORT).show();
} etMessage.setText("");

// BroadcastReceiver for incoming SMS


private BroadcastReceiver smsReceiver = new BroadcastReceiver() private void checkSmsPermission() {
{ if (ContextCompat.checkSelfPermission(this,
@Override Manifest.permission.SEND_SMS) !=
public void onReceive(Context context, Intent intent) { PackageManager.PERMISSION_GRANTED ||
if ContextCompat.checkSelfPermission(this,
(intent.getAction().equals("android.provider.Telephony.SMS_RECEIV Manifest.permission.RECEIVE_SMS) !=
ED")) { PackageManager.PERMISSION_GRANTED ||
Bundle bundle = intent.getExtras(); ContextCompat.checkSelfPermission(this,
if (bundle != null) { Manifest.permission.READ_PHONE_STATE) !=
try { PackageManager.PERMISSION_GRANTED) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) { ActivityCompat.requestPermissions(this,
for (Object pdu : pdus) { new String[]{
SmsMessage sms = Manifest.permission.SEND_SMS,
SmsMessage.createFromPdu((byte[]) pdu); Manifest.permission.RECEIVE_SMS,
String sender =
sms.getDisplayOriginatingAddress(); Manifest.permission.READ_PHONE_STATE
String message = sms.getMessageBody(); },
tvReceivedSMS.setText("From: " + sender + "\ SMS_PERMISSION_CODE);
nMessage: " + message); }
} }
}
} catch (Exception e) { @Override
e.printStackTrace(); protected void onDestroy() {
} super.onDestroy();
} // Unregister receiver when activity is destroyed
} unregisterReceiver(smsReceiver);
} }
}; }
Pr.31
Xml code: Manifest.xml
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android" <manifest
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/andro
xmlns:tools="http://schemas.android.com/tools" id"
android:layout_width="match_parent" xmlns:tools="http://schemas.android.com/tools">
android:layout_height="match_parent"
android:id="@+id/map" <application
android:name="com.google.android.gms.maps.SupportMapFragment" android:allowBackup="true"
tools:context=".MainActivity"/>
java code: android:dataExtractionRules="@xml/data_extraction_rule
package com.example.mapwithmarker; s"
android:fullBackupContent="@xml/backup_rules"
import androidx.annotation.NonNull; android:icon="@mipmap/ic_launcher"
import androidx.appcompat.app.AppCompatActivity; android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
import android.os.Bundle; android:supportsRtl="true"
android:theme="@style/Theme.Mapwithmarker"
import com.google.android.gms.maps.CameraUpdate; tools:targetApi="31">
import com.google.android.gms.maps.CameraUpdateFactory; <activity
import com.google.android.gms.maps.GoogleMap; android:name=".MainActivity"
import com.google.android.gms.maps.OnMapReadyCallback; android:exported="true">
import com.google.android.gms.maps.SupportMapFragment; <intent-filter>
import com.google.android.gms.maps.model.LatLng; <action
import com.google.android.gms.maps.model.MarkerOptions; android:name="android.intent.action.MAIN" />

<category
public class MainActivity extends AppCompatActivity implements android:name="android.intent.category.LAUNCHER" />
OnMapReadyCallback { </intent-filter>
GoogleMap mMap; </activity>
@Override <meta-data
protected void onCreate(Bundle savedInstanceState)
{ android:name="com.google.android.geo.API_KEY"
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); android:value="AIzaSyDYiArGJfp8os_lMpw5wlR8UlF-
SupportMapFragment mapFragment= (SupportMapFragment) OY86A98" />
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this); </application>

} </manifest>
@Override Add dependencies in buildgradle: module app
public void onMapReady(@NonNull GoogleMap googleMap) implementation("com.google.android.gms:play-services-
{ maps:18.1.0")
mMap= googleMap;
LatLng latLng=new LatLng(19.0728,72.8826);
MarkerOptions markerOptions=new
MarkerOptions().position(latLng).title("Mumbai");
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16
f));

}
}

Write a program to locate the user's current location.


Xml code: locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDE
<?xml version="1.0" encoding="utf-8"?> R, 5000, 10, locationListener);
<LinearLayout // Request location updates from Network Provider
xmlns:android="http://schemas.android.com/apk/res/an
droid" locationManager.requestLocationUpdates(LocationManager.NETWORK_PR
android:layout_width="match_parent" OVIDER, 5000, 10, locationListener);
android:layout_height="match_parent" }
android:orientation="vertical" } catch (Exception e) {
android:padding="20dp"> Log.e("LocationError", "Error getting location: " + e.getMessage());
}
<TextView }
android:id="@+id/locationTextView" private final LocationListener locationListener = new LocationListener() {
android:layout_width="wrap_content" @Override
android:layout_height="wrap_content" public void onLocationChanged(@NonNull Location location) {
android:text="Fetching location..." double latitude = location.getLatitude();
android:textSize="18sp" double longitude = location.getLongitude();
android:textStyle="bold" /> locationTextView.setText("Latitude: " + latitude + "\nLongitude: " +
longitude);
</LinearLayout> // Log.d("Location Update", "Lat: " + latitude + ", Lng: " + longitude);
Java code: //Toast.makeText(MainActivity.this, "Lat: " + latitude + ", Lng: " +
package com.example.currentlocationmanager; longitude, Toast.LENGTH_LONG).show();
}
@Override
import android.Manifest; public void onProviderDisabled(@NonNull String provider) {
import android.annotation.SuppressLint; Toast.makeText(MainActivity.this, "Please Enable GPS",
import android.content.Context; Toast.LENGTH_SHORT).show();
import android.content.pm.PackageManager; }
import android.location.Location; };
import android.location.LocationListener;
import android.location.LocationManager; @Override
import android.os.Bundle; public void onRequestPermissionsResult(int requestCode, @NonNull
import android.util.Log; String[] permissions, @NonNull int[] grantResults) {
import android.widget.TextView; super.onRequestPermissionsResult(requestCode, permissions,
import android.widget.Toast; grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
import androidx.annotation.NonNull; if (grantResults.length > 0 && grantResults[0] ==
import androidx.appcompat.app.AppCompatActivity; PackageManager.PERMISSION_GRANTED) {
import androidx.core.app.ActivityCompat; getLocation();
import androidx.core.content.ContextCompat; } else {
Toast.makeText(this, "Permission Denied",
public class MainActivity extends AppCompatActivity Toast.LENGTH_SHORT).show();
{ }
}
private static final int }
LOCATION_PERMISSION_REQUEST_CODE = 1;
private LocationManager locationManager;
private TextView locationTextView;

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

locationTextView =
findViewById(R.id.locationTextView);
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

// Check and request location permission


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
} else {
getLocation();
}
Pr.32
Xml code: Java code:
<?xml version="1.0" encoding="utf-8"?> package com.example.maproute;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/andr import androidx.appcompat.app.AppCompatActivity;
oid"
android:layout_width="match_parent" import android.content.Intent;
android:layout_height="match_parent" import android.net.Uri;
android:orientation="vertical" import android.os.Bundle;
android:padding="16dp"> import android.view.View;
import android.widget.Button;
<EditText import android.widget.EditText;
android:id="@+id/et1"
android:layout_width="match_parent" public class MainActivity extends AppCompatActivity {
android:layout_height="wrap_content" EditText et1,et2;
android:hint="Enter Source (City, Address, etc.)" Button btnfindroute;
android:inputType="text"/> @Override
<EditText protected void onCreate(Bundle savedInstanceState) {
android:id="@+id/et2" super.onCreate(savedInstanceState);
android:layout_width="match_parent" setContentView(R.layout.activity_main);
android:layout_height="wrap_content" et1=findViewById(R.id.et1);
android:hint="Enter Destination (City, Address, et2=findViewById(R.id.et2);
etc.)" btnfindroute=findViewById(R.id.btnFindRoute);
android:inputType="text"/> btnfindroute.setOnClickListener(new
View.OnClickListener() {
<Button @Override
android:id="@+id/btnFindRoute" public void onClick(View v) {
android:layout_width="match_parent" String s1=et1.getText().toString();
android:layout_height="wrap_content" String s2=et2.getText().toString();
android:text="Find Route" Uri
android:layout_marginTop="10dp"/> uri=Uri.parse("https://www.google.co.in/maps/dir/"+s1+"/"+
</LinearLayout> s2);
Intent intent=new
Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
});

}
}

You might also like