Unit 3
(2 Marks)
1. What is an Activity in Android?
An Activity in Android represents a single screen with a user interface. It is the entry point
for user interaction with an app and handles UI elements and user events.
2. Define Intent in Android.
An Intent is a messaging object used to request an action from another component (e.g.,
launching an activity, sending data, starting a service).
3. Mention any two types of Intents.
Explicit Intent – Targets a specific component within the app (e.g., start a specific
activity).
Implicit Intent – Declares a general action to perform, allowing other apps to handle
it (e.g., open a web page or send an email).
4. What is a Fragment in Android?
A Fragment is a reusable portion of the UI inside an activity. It represents part of a user
interface and can be combined with other fragments in a single activity.
5. State the purpose of a Broadcast Receiver.
A Broadcast Receiver listens for and responds to system-wide broadcast announcements
(e.g., battery low, SMS received, airplane mode changed).
(3 Marks)
1. Explain the role of an Intent Filter.
An Intent Filter in Android declares the capabilities of a component (like an Activity,
Service, or BroadcastReceiver).
It tells the system what type of intents the component can handle.
For example, an activity with an intent filter for ACTION_VIEW and a URL will respond when
a user wants to view a webpage.
Example:
xml
CopyEdit
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
2. List and explain the two main types of Intents.
Type of
Description
Intent
Explicit Specifies the exact component (class name) to be launched. Used within
Intent apps.
Implicit Does not specify a component. The system searches for matching intent
Intent filters.
Example:
Explicit: Start a specific activity in the same app.
Implicit: Share a photo via available apps that support sharing.
3. What is the use of Content Providers in Android?
A Content Provider manages access to a structured set of data. It allows data sharing
between different apps.
Used to store and retrieve data from databases, files, or the web.
Apps like Contacts or Media store expose their data using content providers.
Example: Accessing contacts using:
java
CopyEdit
Uri uri = ContactsContract.Contacts.CONTENT_URI;
4. Briefly describe the service component in Android.
A Service is an Android component that runs in the background to perform long-running
tasks without a user interface.
Used for tasks like music playback, downloading files, etc.
Can be started (run indefinitely) or bound (interact with other components).
5. What are the basic steps to start a new Activity?
1. Create an Intent:
java
CopyEdit
Intent intent = new Intent(this, SecondActivity.class);
2. Start the Activity:
java
CopyEdit
startActivity(intent);
3. Declare the Activity in AndroidManifest.xml:
xml
CopyEdit
<activity android:name=".SecondActivity" />
(5 Marks)
1. Describe the lifecycle of an Activity with a diagram.
Activity Lifecycle States:
1. onCreate() – Called when the activity is first created.
2. onStart() – Activity becomes visible.
3. onResume() – Activity starts interacting with the user.
4. onPause() – Called when the activity is partially obscured.
5. onStop() – Called when the activity is no longer visible.
6. onRestart() – Called before onStart() when restarting the activity.
7. onDestroy() – Called before the activity is destroyed.
Diagram:
scss
CopyEdit
onCreate()
↓
onStart()
↓
onResume()
↓
[Activity Running]
↑
onPause()
↓
onStop()
↑
onRestart()
↓
onDestroy()
2. Compare Fragment Lifecycle with Activity Lifecycle
Aspect Activity Fragment
onAttach(), onCreateView(),
Creation onCreate()
onActivityCreated()
UI Uses XML layout in
UI created in onCreateView()
Handling setContentView()
Running onResume() onResume()
Pause onPause() onPause()
Destroy onDestroy() onDestroyView(), onDetach()
Fragment lifecycle is closely tied to the host Activity’s lifecycle.
3. Explain how data is sent and received between two Activities.
Sending Data (From Activity A):
java
CopyEdit
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("username", "JohnDoe");
startActivity(intent);
Receiving Data (In Activity B):
java
CopyEdit
String user = getIntent().getStringExtra("username");
Using startActivityForResult() for returning data:
java
CopyEdit
// In FirstActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, 1);
java
CopyEdit
// In SecondActivity
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "Success");
setResult(RESULT_OK, returnIntent);
finish();
4. Discuss the role and structure of a Broadcast Receiver with example code.
Role:
A Broadcast Receiver listens for and responds to system-wide events or custom
broadcasts.
Example – Listening to Airplane Mode:
Java Code:
java
CopyEdit
public class AirplaneReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Airplane Mode Changed", Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml:
xml
CopyEdit
<receiver android:name=".AirplaneReceiver">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE" />
</intent-filter>
</receiver>
5. Write a short note on Content Providers and their significance.
Content Providers are used to manage and share app data securely between
applications.
They abstract data access using a URI-based interface.
Commonly used for sharing data like contacts, media, and calendar events.
Access is controlled via permissions, ensuring security.
Example:
java
CopyEdit
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Significance:
Facilitates data sharing across apps.
Enables modular data access.
Ensures security and encapsulation.
(8 Marks)
1. Explain the complete Activity lifecycle with code examples and use cases.
Lifecycle Methods:
Method Purpose
onCreate() Initialize activity, load layout & setup code
onStart() Activity becomes visible
onResume() Activity is in the foreground
onPause() Activity partially hidden
onStop() Activity is completely hidden
onRestart() Called after stop, before start
onDestroy() Clean up resources
Code Example:
java
CopyEdit
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Lifecycle", "onCreate");
}
@Override
protected void onStart() {
super.onStart();
Log.d("Lifecycle", "onStart");
}
Use Case:
Save user data in onPause()
Resume tasks in onResume()
Release resources in onStop() or onDestroy()
2. Describe how to use Intents to navigate between multiple Activities, passing data.
Explicit Intent (with data):
Activity A:
java
CopyEdit
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("username", "JohnDoe");
startActivity(intent);
Activity B:
java
CopyEdit
String name = getIntent().getStringExtra("username");
textView.setText(name);
Returning Data with Result:
Activity A:
java
CopyEdit
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, 1);
Activity B:
java
CopyEdit
Intent resultIntent = new Intent();
resultIntent.putExtra("result", "Success");
setResult(RESULT_OK, resultIntent);
finish();
Benefits:
Enables modular screen design
Transfers data across activities
3. Discuss the importance and usage of Fragments in building flexible UIs.
What is a Fragment?
A Fragment is a reusable part of the UI that lives within an Activity.
Suitable for dynamic UIs and tablet optimization.
Benefits:
Reusability of UI components
Responsive multi-pane layouts
Easier management of large screen designs
Usage Example:
Fragment XML:
xml
CopyEdit
<fragment android:name="com.example.MyFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Fragment Java:
java
CopyEdit
public class MyFragment extends Fragment {
@Override
public View onCreateView(...) {
return inflater.inflate(R.layout.fragment_layout, container, false);
}
}
4. Explain the process of creating a custom Service and how it runs in the
background.
Steps to Create a Service:
1. Create a class extending Service:
java
CopyEdit
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Background task
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
2. Declare in AndroidManifest.xml:
xml
CopyEdit
<service android:name=".MyService"/>
3. Start the service from an Activity:
java
CopyEdit
startService(new Intent(this, MyService.class));
Use Cases:
Music playback
Downloading files
Location tracking
5. Describe how Android manages communication between apps using Content
Providers.
Role of Content Providers:
Facilitate data sharing between apps using a URI-based interface.
Work like a database layer for external access.
Example Access:
java
CopyEdit
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
Implementing a Custom Content Provider:
1. Extend ContentProvider class
2. Override query(), insert(), update(), delete(), getType()
3. Declare in AndroidManifest.xml
Significance:
Ensures secure, controlled access to app data
Enables modular app design
Commonly used in Contacts, Media, Calendar
(12 Marks)
1. Create an Android app structure that uses Activities, Fragments, and Intents.
Explain each component’s role.
Structure Overview:
MainActivity → Hosts a Fragment and navigates to SecondActivity via Intent.
Fragment → Handles part of the UI.
SecondActivity → Receives data from MainActivity.
MainActivity.java
java
CopyEdit
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, new SampleFragment())
.commit();
}
public void openSecondActivity(String msg) {
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("message", msg);
startActivity(intent);
}
}
SampleFragment.java
java
CopyEdit
public class SampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sample, container, false);
Button btn = view.findViewById(R.id.open_btn);
btn.setOnClickListener(v -> ((MainActivity) getActivity()).openSecondActivity("Hello
from Fragment!"));
return view;
}
}
SecondActivity.java
java
CopyEdit
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String msg = getIntent().getStringExtra("message");
// Show in TextView
}
}
Explanation:
Activity: Entry point, handles navigation.
Fragment: Reusable, modular UI component.
Intent: Used to pass data between Activities.
2. Design a broadcast receiver to handle network change events. Include code and
explanation.
NetworkChangeReceiver.java
java
CopyEdit
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
Toast.makeText(context, "Connected to Internet", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml
xml
CopyEdit
<receiver android:name=".NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
Explanation:
Receives a broadcast when the network state changes.
Provides real-time network feedback.
3. Develop a data sharing mechanism between two apps using Content Providers.
Include XML and Java snippets.
Step 1: Create ContentProvider in App A
java
CopyEdit
public class MyProvider extends ContentProvider {
public static final Uri CONTENT_URI =
Uri.parse("content://com.example.myprovider/users");
private static final HashMap<String, String> PROJECTION_MAP;
@Override
public boolean onCreate() {
// Initialize DB
return true;
}
@Override
public Cursor query(...) {
// Return data from SQLite
}
@Override
public Uri insert(...) {
// Insert into DB
}
}
AndroidManifest.xml
xml
CopyEdit
<provider
android:name=".MyProvider"
android:authorities="com.example.myprovider"
android:exported="true"/>
Step 2: Access from App B
java
CopyEdit
Cursor cursor = getContentResolver().query(
Uri.parse("content://com.example.myprovider/users"),
null, null, null, null
);
Explanation:
App A exposes data.
App B queries it using the ContentResolver.
4. Design a multi-screen app that uses Intents for data passing and Activity result
handling. Explain its full lifecycle behavior.
MainActivity.java
java
CopyEdit
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("name", "Alice");
startActivityForResult(intent, 1);
SecondActivity.java
java
CopyEdit
Intent result = new Intent();
result.putExtra("result", "Hi, Alice!");
setResult(RESULT_OK, result);
finish();
MainActivity (Receiving Result)
java
CopyEdit
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
String msg = data.getStringExtra("result");
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
Lifecycle Behavior:
1. MainActivity → onCreate, onResume
2. Navigates → SecondActivity → onCreate, onResume
3. Back to Main → onActivityResult, onResume
5. Evaluate the differences between Activity, Service, and BroadcastReceiver. When
should each be used? Justify with examples.
Component Purpose Example Use Case
Activity User interface interaction Login screen, Settings page
Service Background work (no UI) Music player, File downloads
Component Purpose Example Use Case
BroadcastReceiver Event-based messaging Battery low, Network changes
When to Use:
Activity: Any screen-based interaction.
Ex: LoginActivity, MainActivity
Service: Long tasks running without UI.
Ex: MyLocationService for GPS tracking.
BroadcastReceiver: Listen to system/app events.
Ex: SMSReceiver to capture incoming SMS.
Code Usage:
Start a Service: startService(new Intent(...))
Register a Receiver: registerReceiver(...)
Launch an Activity: startActivity(new Intent(...))