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

Android App UI and Functionality Guide

The document contains multiple Android application examples, each with its own layout and functionality. The first example demonstrates text manipulation with buttons to increase/decrease font size and change text color. Subsequent examples include a simple calculator, a drawing app, and a to-do list application utilizing a content provider for data management.

Uploaded by

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

Android App UI and Functionality Guide

The document contains multiple Android application examples, each with its own layout and functionality. The first example demonstrates text manipulation with buttons to increase/decrease font size and change text color. Subsequent examples include a simple calculator, a drawing app, and a to-do list application utilizing a content provider for data management.

Uploaded by

kevin.112210
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Exp1

activity_main.xml

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

<LinearLayout xmlns:android="[Link]

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:orientation="vertical"

android:padding="20dp">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello Android!"

android:textSize="20sp"

android:textColor="#000000"

android:padding="16dp" />

<Button

android:id="@+id/btnIncrease"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Increase Font" />

<Button

android:id="@+id/btnDecrease"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Decrease Font"

android:layout_marginTop="8dp" />

<Button

android:id="@+id/btnColor"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Change Color"

android:layout_marginTop="8dp" />

</LinearLayout>

[Link]

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

TextView textView;
Button btnIncrease, btnDecrease, btnColor;
float currentSize = 20f;
Random random = new Random();

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

textView = findViewById([Link]);
btnIncrease = findViewById([Link]);
btnDecrease = findViewById([Link]);
btnColor = findViewById([Link]);

[Link](v -> {
currentSize += 2;
[Link](currentSize);
});

[Link](v -> {
if (currentSize > 10) {
currentSize -= 2;
[Link](currentSize);
}
});

[Link](v -> {
int color = [Link]([Link](256), [Link](256),
[Link](256));
[Link](color);
});
}
}

[Link]

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<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/[Link]">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>

</application>

</manifest>

Exp 2 :

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">

<EditText
android:id="@+id/num1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal"
android:padding="8dp" />

<EditText
android:id="@+id/num2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal"
android:padding="8dp"
android:layout_marginTop="8dp" />

<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result will appear here"
android:textSize="18sp"
android:layout_marginTop="16dp" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginTop="16dp">

<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />

<Button
android:id="@+id/btnSub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:layout_marginStart="8dp" />

<Button
android:id="@+id/btnMul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="x"
android:layout_marginStart="8dp" />

<Button
android:id="@+id/btnDiv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:layout_marginStart="8dp" />
</LinearLayout>

</LinearLayout>

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

EditText num1, num2;


TextView result;
Button btnAdd, btnSub, btnMul, btnDiv;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

num1 = findViewById([Link].num1);
num2 = findViewById([Link].num2);
result = findViewById([Link]);
btnAdd = findViewById([Link]);
btnSub = findViewById([Link]);
btnMul = findViewById([Link]);
btnDiv = findViewById([Link]);

[Link](v -> calculate('+'));


[Link](v -> calculate('-'));
[Link](v -> calculate('*'));
[Link](v -> calculate('/'));
}
private void calculate(char operator) {
String s1 = [Link]().toString();
String s2 = [Link]().toString();

if ([Link]() || [Link]()) {
[Link]("Please enter both numbers");
return;
}

double n1 = [Link](s1);
double n2 = [Link](s2);
double res = 0;

switch (operator) {
case '+':
res = n1 + n2;
break;
case '-':
res = n1 - n2;
break;
case '*':
res = n1 * n2;
break;
case '/':
if (n2 == 0) {
[Link]("Cannot divide by zero");
return;
}
res = n1 / n2;
break;
}

[Link]("Result: " + res);


}
}

[Link]

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]
<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/[Link]">

<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>

</application>

</manifest>

exp3:

[Link]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<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/[Link]">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>

</application>

</manifest>

[Link]

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView(new MyCanvas(this));
}

// Custom View for Drawing


public static class MyCanvas extends View {
private Paint paint;
private Path path;

public MyCanvas([Link] context) {


super(context);
paint = new Paint();
[Link]([Link]);
[Link](8);
[Link]([Link]);
[Link](true);
path = new Path();
}

@Override
protected void onDraw(Canvas canvas) {
[Link](canvas);
[Link](path, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
float x = [Link]();
float y = [Link]();

switch ([Link]()) {
case MotionEvent.ACTION_DOWN:
[Link](x, y);
break;
case MotionEvent.ACTION_MOVE:
[Link](x, y);
break;
}
invalidate();
return true;
}
}
}

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

<FrameLayout xmlns:android="[Link]

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#FFFFFF">

</FrameLayout>

Exp4:
[Link]

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<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/[Link]">

<activity
android:name=".MainActivity"
android:exported="true"
android:theme="@style/[Link]">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>

<provider
android:name=".MainActivity$TodoProvider"
android:authorities="[Link]"
android:exported="false" />
</application>

</manifest>

[Link]

package [Link];

import [Link].*;
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link].*;
import [Link];

public class MainActivity extends AppCompatActivity {


EditText inputTask;
Button addButton, updateButton;
ListView listView;
SimpleCursorAdapter adapter;
long selectedId = -1;
Uri CONTENT_URI = [Link]("content://[Link]/todo");

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

inputTask = findViewById([Link]);
addButton = findViewById([Link]);
updateButton = findViewById([Link]);
listView = findViewById([Link]);

String[] from = {"task"};


int[] to = {[Link].text1};
adapter = new SimpleCursorAdapter(this, [Link].simple_list_item_1, null,
from, to, 0);
[Link](adapter);
showTasks();

// CREATE
[Link](v -> {
String task = [Link]().toString().trim();
if ([Link]()) return;
ContentValues values = new ContentValues();
[Link]("task", task);
getContentResolver().insert(CONTENT_URI, values);
[Link]("");
showTasks();
});

// READ + SELECT FOR UPDATE


[Link]((parent, view, position, id) -> {
selectedId = id;
Cursor c = (Cursor) [Link](position);
[Link]([Link]([Link]("task")));
});

// UPDATE
[Link](v -> {
if (selectedId == -1) return;
ContentValues values = new ContentValues();
[Link]("task", [Link]().toString());
Uri uri = [Link](CONTENT_URI, selectedId);
getContentResolver().update(uri, values, null, null);
[Link](this, "Task Updated", Toast.LENGTH_SHORT).show();
[Link]("");
selectedId = -1;
showTasks();
});

// DELETE
[Link]((parent, view, position, id) -> {
Uri deleteUri = [Link](CONTENT_URI, id);
getContentResolver().delete(deleteUri, null, null);
[Link](this, "Task Deleted", Toast.LENGTH_SHORT).show();
showTasks();
return true;
});
}

private void showTasks() {


Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, null);
[Link](cursor);
}

// ---------------- SQLite Helper ----------------


public static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "TodoDB", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
[Link]("CREATE TABLE todo(_id INTEGER PRIMARY KEY AUTOINCREMENT, task
TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
[Link]("DROP TABLE IF EXISTS todo");
onCreate(db);
}
}

public static class TodoProvider extends ContentProvider {


static final String AUTHORITY = "[Link]";
static final String TABLE = "todo";
static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
[Link](AUTHORITY, TABLE, 1);
[Link](AUTHORITY, TABLE + "/#", 2);
}

SQLiteDatabase db;

@Override
public boolean onCreate() {
db = new DBHelper(getContext()).getWritableDatabase();
return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
return [Link](TABLE, null, null, null, null, null, null);
}

@Override
public Uri insert(Uri uri, ContentValues values) {
[Link](TABLE, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if ([Link](uri) == 2) {
String id = [Link]();
return [Link](TABLE, "_id=?", new String[]{id});
}
return 0;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
if ([Link](uri) == 2) {
String id = [Link]();
return [Link](TABLE, values, "_id=?", new String[]{id});
}
return 0;
}

@Override public String getType(Uri uri) { return null; }


}
}

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

<LinearLayout xmlns:android="[Link]

android:orientation="vertical"

android:padding="16dp"

android:layout_width="match_parent"

android:layout_height="match_parent">

<EditText

android:id="@+id/inputTask"

android:hint="Enter or Edit Task"

android:layout_width="match_parent"

android:layout_height="wrap_content"/>

<Button
android:id="@+id/addButton"

android:text="Add Task"

android:layout_width="match_parent"

android:layout_height="wrap_content"/>

<Button

android:id="@+id/updateButton"

android:text="Update Task"

android:layout_width="match_parent"

android:layout_height="wrap_content"/>

<ListView

android:id="@+id/listView"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

</LinearLayout>

Exp5:

Activity_main.xml
<LinearLayout xmlns:android="[Link]

android:orientation="vertical" android:padding="16dp"

android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center">

<Button android:id="@+id/notify" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="Show Notification"/>

</LinearLayout>

[Link]
package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends AppCompatActivity {

private static final String CHANNEL_ID = "sample_channel";

private static final int NOTIFICATION_ID = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

// Ask permission first (Android 13+)

askNotificationPermission();

// Create notification channel


createNotificationChannel();

// Button click listener

Button button = findViewById([Link]);

[Link](v -> showNotification());

private void askNotificationPermission() {

if ([Link].SDK_INT >= Build.VERSION_CODES.TIRAMISU) {

if ([Link](

this, [Link].POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED) {

[Link](

this,

new String[]{[Link].POST_NOTIFICATIONS},

);

private void createNotificationChannel() {

if ([Link].SDK_INT >= Build.VERSION_CODES.O) {

NotificationChannel channel = new NotificationChannel(

CHANNEL_ID,

"Simple Channel",

NotificationManager.IMPORTANCE_DEFAULT
);

[Link]("Sample Notification Channel");

NotificationManager manager = getSystemService([Link]);

if (manager != null) {

[Link](channel);

private void showNotification() {

Intent intent = new Intent(this, [Link]);

PendingIntent pendingIntent = [Link](

this,

0,

intent,

PendingIntent.FLAG_IMMUTABLE

);

[Link] builder = new [Link](this,


CHANNEL_ID)

.setSmallIcon([Link].ic_dialog_info)

.setContentTitle("Hello!")

.setContentText("This is a simple notification.")

.setPriority(NotificationCompat.PRIORITY_DEFAULT)

.setContentIntent(pendingIntent)

.setAutoCancel(true);
NotificationManager manager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);

if (manager != null) {

[Link](NOTIFICATION_ID, [Link]());

[Link]

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

<manifest xmlns:android="[Link]

xmlns:tools="[Link]

<!-- Needed for Android 13+ -->

<uses-permission android:name="[Link].POST_NOTIFICATIONS" />

<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/[Link]"

tools:targetApi="31">

<activity
android:name=".MainActivity"

android:exported="true"

android:theme="@style/[Link]">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Exp6:
[Link]

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

<manifest xmlns:android="[Link]

package="[Link]">

<!-- SMS permissions -->

<uses-feature

android:name="[Link]"

android:required="false" />

<uses-permission android:name="[Link].RECEIVE_SMS"/>

<uses-permission android:name="[Link].READ_SMS"/>
<application

android:allowBackup="true"

android:label="@string/app_name"

android:theme="@style/[Link]">

<activity

android:name=".MainActivity"

android:exported="true">

<intent-filter>

<action android:name="[Link]"/>

<category android:name="[Link]"/>

</intent-filter>

</activity>

<activity

android:name=".AlertActivity"

android:exported="true"

android:theme="@style/[Link]"/>

<receiver

android:name=".SmsReceiver"

android:exported="true"

android:permission="[Link].BROADCAST_SMS">

<intent-filter>

<action android:name="[Link].SMS_RECEIVED"/>

</intent-filter>

</receiver>
</application>

</manifest>

[Link]
package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

// adb emu sms send +911234567890 "Test message"

public class MainActivity extends AppCompatActivity {

private static final int SMS_PERMISSION_CODE = 101;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

if ([Link](this, [Link].RECEIVE_SMS)

!= PackageManager.PERMISSION_GRANTED) {

[Link](this,

new String[]{

[Link].RECEIVE_SMS,

[Link].READ_SMS
},

SMS_PERMISSION_CODE);

[Link]
package [Link];

import [Link];

import [Link];

import [Link];

public class AlertActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

String sender = getIntent().getStringExtra("sender");

String message = getIntent().getStringExtra("message");

new [Link](this)

.setTitle("New SMS from " + sender)

.setMessage(message)

.setPositiveButton("OK", (d, w) -> finish())

.setCancelable(false)

.show();

}
}

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class SmsReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

try {

if ([Link]().equals("[Link].SMS_RECEIVED")) {

Bundle bundle = [Link]();

if (bundle == null) return;

Object[] pdus = (Object[]) [Link]("pdus");

if (pdus == null) return;

String format = [Link]("format");

StringBuilder messageBody = new StringBuilder();

String sender = "";


for (Object pdu : pdus) {

SmsMessage sms;

if ([Link].SDK_INT >= [Link].VERSION_CODES.M) {

sms = [Link]((byte[]) pdu, format);

} else {

sms = [Link]((byte[]) pdu);

sender = [Link]();

[Link]([Link]());

// open alert activity

Intent i = new Intent(context, [Link]);

[Link]("sender", sender);

[Link]("message", [Link]());

[Link](Intent.FLAG_ACTIVITY_NEW_TASK);

[Link](i);

} catch (Exception e) {

Log.e("SmsReceiver", "Error handling SMS", e);

activity_main.xml
<LinearLayout xmlns:android="[Link]

android:orientation="vertical"

android:gravity="center"
android:layout_width="match_parent"

android:layout_height="match_parent">

<Button

android:id="@+id/sendBroadcast"

android:text="Send Broadcast"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

</LinearLayout>

Exp 7

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

<manifest xmlns:android="[Link]

package="[Link]">

<!-- Required for exact alarms on Android 12+ -->

<uses-permission android:name="[Link].SCHEDULE_EXACT_ALARM" />

<application

android:allowBackup="true"

android:label="AlarmSample"

android:supportsRtl="true"

android:theme="@style/[Link]">

<receiver

android:name=".AlarmReceiver"

android:exported="true" />
<activity android:name=".MainActivity"

android:exported="true">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends AppCompatActivity {

private PendingIntent pendingIntent;

private AlarmManager alarmManager;


@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(this, [Link]);

pendingIntent = [Link](this, 0, intent,


PendingIntent.FLAG_IMMUTABLE);

Button set = findViewById([Link]);

Button cancel = findViewById([Link]);

[Link](v -> scheduleAlarm());

[Link](v -> {

[Link](pendingIntent);

[Link](this, "Alarm cancelled", Toast.LENGTH_SHORT).show();

});

private void scheduleAlarm() {

try {

// Check permission for exact alarms (Android 12+)

if ([Link].SDK_INT >= Build.VERSION_CODES.S) {

if (![Link]()) {

[Link](this, "Exact alarm permission required",


Toast.LENGTH_LONG).show();
Intent intent = new
Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);

startActivity(intent);

return;

long triggerTime = [Link]() + 10_000; // 10 seconds

[Link](AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);

[Link](this, "Alarm set for 10 seconds later", Toast.LENGTH_SHORT).show();

} catch (SecurityException e) {

[Link](this, "SecurityException: permission needed",


Toast.LENGTH_LONG).show();

if ([Link].SDK_INT >= Build.VERSION_CODES.S) {

Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);

startActivity(intent);

}
[Link]
package [Link];

import [Link];

import [Link];

import [Link];

import [Link];
public class AlarmReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

[Link](context, " Alarm Fired!", Toast.LENGTH_LONG).show();

Activity_main.xml

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

<LinearLayout xmlns:android="[Link]

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:orientation="vertical"

android:padding="20dp">

<Button

android:id="@+id/set"

android:text="Set Alarm (10s)"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="10dp" />

<Button

android:id="@+id/cancel"

android:text="Cancel Alarm"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:padding="10dp"

android:layout_marginTop="16dp" />

</LinearLayout>

Exp 8:
[Link]
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="[Link]

package="[Link]">

<!-- Permissions for GPS -->

<uses-permission android:name="[Link].ACCESS_FINE_LOCATION" />

<uses-permission android:name="[Link].ACCESS_COARSE_LOCATION" />

<application

android:allowBackup="true"

android:label="GPSSample"

android:supportsRtl="true"

android:theme="@style/[Link]">

<activity

android:name=".MainActivity"

android:exported="true">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>
</application>

</manifest>

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends AppCompatActivity implements LocationListener {

private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

private LocationManager locationManager;

private TextView locationView;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);
setContentView([Link].activity_main);

locationView = findViewById([Link]);

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Check and request permission

if ([Link](this,
[Link].ACCESS_FINE_LOCATION)

!= PackageManager.PERMISSION_GRANTED) {

[Link](this,

new String[]{[Link].ACCESS_FINE_LOCATION},

LOCATION_PERMISSION_REQUEST_CODE);

} else {

startLocationUpdates();

private void startLocationUpdates() {

if ([Link](this,
[Link].ACCESS_FINE_LOCATION)

== PackageManager.PERMISSION_GRANTED) {

try {

[Link](

LocationManager.GPS_PROVIDER,

5000, // 5 seconds

5, // 5 meters

this

);
[Link](this, "Fetching GPS location...", Toast.LENGTH_SHORT).show();

} catch (SecurityException e) {

[Link](this, "Permission error: " + [Link](),


Toast.LENGTH_SHORT).show();

@Override

public void onLocationChanged(@NonNull Location location) {

String text = "Latitude: " + [Link]() + "\nLongitude: " +


[Link]();

[Link](text);

@Override

public void onProviderEnabled(@NonNull String provider) {

[Link](this, "GPS Enabled", Toast.LENGTH_SHORT).show();

@Override

public void onProviderDisabled(@NonNull String provider) {

[Link](this, "GPS Disabled", Toast.LENGTH_SHORT).show();

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,

@NonNull int[] grantResults) {

[Link](requestCode, permissions, grantResults);


if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {

if ([Link] > 0 && grantResults[0] ==


PackageManager.PERMISSION_GRANTED) {

startLocationUpdates();

} else {

[Link](this, "Location permission denied", Toast.LENGTH_LONG).show();

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

<LinearLayout xmlns:android="[Link]

android:orientation="vertical"

android:padding="16dp"

android:gravity="center"

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/loc"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Location: Unknown"

android:textSize="18sp"

android:padding="10dp" />

</LinearLayout>

Common questions

Powered by AI

Android applications ensure adaptive user interfaces through the use of layout managers like LinearLayout and by employing flexible layouts such as FrameLayout or ConstraintLayout. These layouts can dynamically adjust their content to fit various screen sizes and orientations by using layout parameters like layout_width and layout_height set to 'match_parent' or 'wrap_content' . Padding and margins (e.g., android:padding="20dp") are used to ensure content is not cramped on smaller screens .

Content Providers can introduce security vulnerabilities if exported inappropriately, as they can allow unauthorized apps to access sensitive data. Proper permissions must be applied, such as android:exported="false", to restrict unauthorized access. Additionally, verifying and validating the data input and output through the provider is crucial to prevent SQL injection attacks . Moreover, restricting URIs and limiting the exposure of data fields help mitigate potential leakage of personal information.

SMS messages are received by defining a BroadcastReceiver with intent-filter for the 'android.provider.Telephony.SMS_RECEIVED' action. Upon reception, the onReceive method processes the incoming message using the SmsMessage class, which retrieves sender and message content. Permissions for RECEIVE_SMS and READ_SMS must be granted to capture SMS events and process them . The implementation includes necessary security checks and logic to handle different Android versions while extracting the message data.

CRUD operations with SQLite in Android involve SQLiteOpenHelper to manage the database. In a ContentProvider, URIs are used to query, insert, update, or delete data. Data is fetched with Cursor and displayed using adapters like SimpleCursorAdapter. INSERT and UPDATE require ContentValues to specify data columns, and DELETE depends on the URI matcher for identifying entries. The provider notifies content changes to update UI components automatically . Security includes validating input to prevent SQL injections and considering database access permissions.

Preventing illegal arithmetic operations, such as division by zero, is achieved using conditional checks before performing the operation. In the calculate function, a specific check for 'if (n2 == 0)' is made before dividing, and an appropriate error message is set to inform the user to prevent crashing or displaying incorrect results . This proactive validation ensures stable application behavior and avoids runtime exceptions.

When implementing a text resizing feature, it is crucial to maintain readability while ensuring that text does not overflow the container. Adjusting the font size should dynamically update the UI without breaking the layout. Safety checks, such as ensuring the font size does not drop below a certain threshold, should be included to avoid unreadably small text sizes, as evidenced by the use of 'if (currentSize > 10)' in the implementation to prevent reducing the text size below 10sp .

Key steps involve: 1) Requesting notification permissions above Android 13 through ActivityCompat. 2) Creating a notification channel using NotificationChannel for Android 8.0 and above, specifying the importance level and description. 3) Building the notification using NotificationCompat.Builder and setting necessary properties like small icon and content text. Finally, 4) Displaying the notification through NotificationManager.notify() method .

Implementing GPS location updates involves acquiring proper permissions: ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION. The application uses LocationManager to request location updates by specifying the GPS_PROVIDER, update time interval, and distance between updates. Implementing the LocationListener interface allows you to react to location changes by updating the UI with the new location information . Handling permission results to reactively manage user denial is also essential in the implementation.

Custom views offer a tailored solution to specific UI needs not covered by standard widgets. They enable developers to create complex and highly engaging interfaces (e.g., custom drawing with MyCanvas), enhancing user experience. However, challenges include added complexity in dealing with custom rendering, requiring a deeper understanding of graphics APIs like Canvas and Path. Implementing touch events demands thoughtful design to manage user interactions effectively . Balancing performance, accessibility, and functionality presents additional hurdles.

The AndroidManifest.xml file serves as the foundational structure for Android applications to declare permissions, activities, services, and other components. It includes intent filters determining the app's interaction with the broader system, as seen in activity declarations with action and category tags. Essential metadata, such as app themes and app-level permissions (e.g., receiving and reading SMS), is also specified to guide the Android system on how to execute the app . This centralized configuration ensures proper application behavior and security policies.

You might also like