0% found this document useful (0 votes)
8 views10 pages

Mad Unit Iv

The document outlines methods for sharing data in Android, including Intents, Content Providers, Shared Preferences, and External Storage. It details the implementation of Content Providers for secure data sharing, including CRUD operations and permissions setup. Additionally, it covers SMS messaging, email sending, and displaying maps using the Google Maps API, along with necessary permissions and code examples.

Uploaded by

shyamala devi
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)
8 views10 pages

Mad Unit Iv

The document outlines methods for sharing data in Android, including Intents, Content Providers, Shared Preferences, and External Storage. It details the implementation of Content Providers for secure data sharing, including CRUD operations and permissions setup. Additionally, it covers SMS messaging, email sending, and displaying maps using the Google Maps API, along with necessary permissions and code examples.

Uploaded by

shyamala devi
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/ 10

UNIT IV

Sharing Data in Android


Sharing data in Android refers to the process of transferring information between different
applications or components within the same application. Android provides multiple methods for
data sharing, depending on the use case and the level of security required.
Ways to share the data in android
 Use Intents for simple sharing (text, images).
 Use Content Providers for secure structured data sharing between apps.
 Use Shared Preferences for lightweight internal data storage.
 Use External Storage for sharing large files.
Content Providers in Android

Definition:

A Content Provider is a component in Android that enables secure sharing of structured data
between applications. It allows an app to store, retrieve, update, and delete data while
maintaining security and permissions.

Why Use Content Providers?

 Allows data sharing between apps securely.


 Provides controlled access to data.
 Manages structured data storage (SQLite, Room, files, etc.).
 Supports multi-user access to data.

How Content Providers Work

1. Data Storage → The provider stores data in SQLite, Room, or another storage
mechanism.
2. URI (Uniform Resource Identifier) → Other apps use a URI to request data.
3. Permissions & Security → The provider ensures that only authorized apps can access
data.
4. CRUD Operations → Other apps can use query, insert, update, and delete to
manipulate data.
Creating a Content Provider (Step-by-Step)

1. Define the Content Provider Class

Create a class that extends ContentProvider and override CRUD methods.


public class MyContentProvider extends ContentProvider {
@Override
public boolean onCreate() {
return true; // Initialize database here
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String
sortOrder) {
return null; // Fetch data from the database
}

@Override
public Uri insert(Uri uri, ContentValues values) {
return null; // Insert data into the database
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0; // Update data in the database
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0; // Delete data from the database
}

@Override
public String getType(Uri uri) {
return null; // Return the MIME type of data
}
}

2. Declare the Provider in AndroidManifest.xml

Register the provider so that it can be accessed by other apps.

<provider
android:name=".MyContentProvider"
android:authorities="com.example.provider"
android:exported="true"
android:grantUriPermissions="true" />

Important:

 android:exported="true" → Allows external apps to access the provider.


 android:authorities="com.example.provider" → Unique authority name used in URIs.
 android:grantUriPermissions="true" → Allows dynamic permission granting.

Using Content Resolver to Access Data

Apps can interact with a Content Provider using ContentResolver.

Example: Query Data


Uri uri = Uri.parse("content://com.example.provider/users");
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
Example: Insert Data
ContentValues values = new ContentValues();
values.put("name", "John Doe");
Uri uri = Uri.parse("content://com.example.provider/users");
getContentResolver().insert(uri, values);

Types of URIs in Content Providers

A URI (Uniform Resource Identifier) identifies the data inside a Content Provider.
The format is:

content://<authority>/<path>/<id>
SMS Messaging in Android

SMS (Short Message Service) messaging in Android allows applications to send, receive, and
manage SMS messages using the Android Telephony API.

1. Sending SMS in Android

Android provides multiple ways to send SMS messages:

A. Using SMS Manager (Direct SMS Sending)

SmsManager allows sending SMS messages without opening the default SMS app.

Example: Sending SMS using SmsManager


SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+1234567890", null, "Hello, this is a test message!", null,
null);

Permissions Required in AndroidManifest.xml:


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

Pros: Sends SMS directly in the background.


❌ Cons: Requires SEND_SMS permission, which Google Play may restrict for privacy reasons.

B. Using Intent (Opens Default SMS App)

This method opens the default messaging app with a pre-filled message.
Example: Sending SMS using an Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("sms:+1234567890"));
intent.putExtra("sms_body", "Hello, this is a test message!");
startActivity(intent);

✅ Pros: No special permission needed.


❌ Cons: Requires user interaction to send the SMS.

2. Receiving SMS in Android

To receive SMS messages in an Android app, you need to use a BroadcastReceiver.

A. Creating an SMS Receiver

1. Register a BroadcastReceiver to listen for incoming SMS.


2. Extract SMS message content from the received intent.

Example: SMS Receiver Implementation


public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent))
{
String sender = smsMessage.getOriginatingAddress();
String messageBody = smsMessage.getMessageBody();

Toast.makeText(context, "SMS from " + sender + ": " + messageBody,


Toast.LENGTH_LONG).show();
}
}
}
}

Permissions Required in AndroidManifest.xml:


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

Register BroadcastReceiver in AndroidManifest.xml:

<receiver android:name=".SmsReceiver" android:exported="true">


<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
✅ Pros: Automatically detects incoming SMS.
❌ Cons: Google Play restricts SMS permissions for security reasons (use only for default
messaging apps).

Sending Email in Android

In Android, you can send emails from your app using different methods. The most common
approaches are:

1. Using an Email Intent (Recommended)


2. Using JavaMail API (For Advanced Email Sending)
3. Using Third-Party Libraries (e.g., JavaMail, SMTP)

1. Sending Email Using an Intent (Recommended)

The easiest and most recommended way to send an email in Android is by using an Intent. This
method opens the default email app with a pre-filled email.

Example: Send Email Using an Intent


Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822"); // MIME type for email
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"recipient@example.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Hello from Android App");
intent.putExtra(Intent.EXTRA_TEXT, "This is a test email.");

try {
startActivity(Intent.createChooser(intent, "Choose an Email Client"));
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(this, "No email client installed.", Toast.LENGTH_SHORT).show();
}

How It Works:

 ACTION_SEND → Opens an email app.


 setType("message/rfc822") → Ensures only email apps are shown.
 EXTRA_EMAIL → Sets the recipient’s email.
 EXTRA_SUBJECT → Sets the subject.
 EXTRA_TEXT → Adds email content.
 createChooser() → Asks the user to pick an email app.

✅ Pros:

 No special permissions required.


 Secure and follows Android guidelines.
❌ Cons:

 User must manually send the email.

Displaying Maps in Android

Android provides Google Maps API to integrate interactive maps into your app. You can use
Google Maps to display locations, get directions, and customize map styles.

1. Steps to Display a Google Map in Android

Step 1: Get a Google Maps API Key

1. Go to Google Cloud Console


2. Create a new project.
3. Enable the Google Maps SDK for Android.
4. Generate an API Key and add it to your project.

Step 2: Add Dependencies in build.gradle

Add the required libraries for Google Maps.

dependencies {
implementation 'com.google.android.gms:play-services-maps:18.1.0'
implementation 'com.google.android.gms:play-services-location:21.0.1'
}

Step 3: Add Permissions in AndroidManifest.xml

Google Maps requires internet access and location permissions.

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Declare the Maps API Key inside the <application> tag.


<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>

Step 4: Add a Map Fragment in activity_main.xml

Use a MapFragment or SupportMapFragment to display the map.

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Step 5: Initialize Google Maps in MainActivity.java

Implement the OnMapReadyCallback interface to load the map.

import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {


private GoogleMap mMap;

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

// Initialize map fragment


SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) {
mapFragment.getMapAsync(this);
}
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

// Set map type


mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

// Add a marker at a location (e.g., New York)


LatLng newYork = new LatLng(40.7128, -74.0060);
mMap.addMarker(new MarkerOptions().position(newYork).title("Marker in New York"));
// Move the camera to the location
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newYork, 10));
}
}

Getting Location Data-


Enabling User Location on Map

To show the user's current location, enable location services.

Step 1: Check Location Permissions

Modify onMapReady() to check and request permissions.


@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}

mMap.setMyLocationEnabled(true);
}
Step 2: Handle Permission Request Result
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1 && grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
}

✅ Now, the map will show the user’s current location!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy