CST 2301 Chapter 12.docx

CST 2301 Chapter 12

Creating a Content Provider:

1. Steps involved:

- Designing a URI for data mapping.

- Inserting a provider element into the manifest file.

- Extending the ContentProvider class.

- Setting permissions.

2. Creating ContentProvider class:

- Right-click on the app folder.

- Define authority (typically using the package name).

- Implement all six methods in the class template.

3. Designing a URI:

- URI (Universal Resource Identifier) uniquely names a provider and its data.

- Example URI: "content://com.code.abdulrahman.cprovider/contacts".

- Three parts: schema ("content://"), authority, and path to a table in the database.

4. UriMatcher:

- Matches incoming Uri with content provider's Uri.

- Initialized with provider's name, path, and return code.

- Usage: uriMatcher.match(uri).

5. onCreate Method Implementation:

- Initializes the content provider on startup.

- Example: creating an SQLite database.

6. Query Method Implementation:

- Retrieves data from the database based on the Uri.

- Uses SQLiteQueryBuilder and Cursor.

- Notifies observer objects about changes in the content provider.

7. Insert Method Implementation:

- Inserts a new row into the database.

- Notifies ContentResolver about the change.

8. Update Method Implementation:

- Updates one or more rows in the database.

- Notifies ContentResolver about the change.

9. Delete Method Implementation:

- Deletes one or more rows from the database.

- Notifies ContentResolver about the change.

10. getType Method Implementation:

- Specifies the content media type (MIME type).

- Returns "vnd.android.cursor.dir" for multiple rows and "vnd.android.cursor.item" for a single row.

11. ContentProvider Code Example:

- Complete code for the ContentProvider class.

- Includes Uri, database creation, and implementation of all six methods.

Running and Testing Content Provider:

1. Main Class Creation:

- Created a main class with storeData() and retrieveData() methods.

- storeData(): Inserts data using ContentResolver.insert().

- retrieveData(): Queries data using ContentResolver.query().

2. Example Code:

- Includes EditText fields for user input.

- Inserts data into the content provider database.

- Retrieves data from the content provider and displays it in a ListView.

3. Testing:

- Users can test the insert() and query() methods.

- Provided instructions to implement update(), delete(), getType(), and onCreate() methods for further testing.

**Content Provider Client:**

1. **Objective:**

- The client app queries data stored in the content provider app's database.

- Displays retrieved results on its screen.

2. **Usage:**

- Utilizes ContentResolver object and its query() method.

- Invokes ContentProvider.query() method.

3. **Example Code:**

- Shows an example of the query() method from the client app.

- Displays the client app querying the content provider and the results obtained.

4. **Testing Instructions:**

- Provided instructions to implement update(), delete(), and insert() methods for the client content provider app.

- Note: Updating the provider's AndroidManifest.xml is necessary, adding writable access to the provider element.

Media Content Streaming Apps:

1. **Required Android Classes:**

- Android Service

- BroadcastReceiver

- MediaPlayer

- VideoView

- Other relevant classes

2. **Demo App Overview:**

- Developed to illustrate the usage of mentioned classes.

- Interface includes four buttons to start and stream media content.

- Demonstrates various functionalities:

- Running radio stations using URLs.

- Playing videos using implicit intents with URLs.

- Playback of remote videos using VideoView.

- Running embedded videos within the app.

3. **Implementation Details:**

- Utilizes Android Service for background tasks.

- Uses BroadcastReceiver for handling broadcasted messages.

- MediaPlayer for audio streaming.

- VideoView for video playback.

- Illustrates how to stream media content both locally and from URLs.

4. **Interface Overview:**

- Figure 12.3 showcases the interface for the demo app.

- Four buttons provided for initiating media streaming.

5. **Future Sections:**

- Further sections will delve into the classes and implementation specifics of the demo app.

Summary of Android Service:

1. **Introduction:**

- Service component runs tasks in the background without a UI.

- Essential for multitasking apps like browsing and listening to music simultaneously.

2. **Service Usage:**

- Runs tasks independently of the app's lifecycle.

- Suitable for tasks not requiring user interaction.

- Can be private (accessible only within the app) or public (accessible by other apps).

3. **Examples of Service Usage:**

- Downloading/uploading via network.

- Background music playback.

- Periodic website monitoring.

- Maintaining connections during interruptions.

4. **Starting and Running Service:**

- Services can be started using `startForegroundService()`.

- Use explicit intent for security.

- Services run indefinitely until explicitly stopped.

5. **Communication with Service:**

- Two methods: command-based communication and binding.

- Binding allows interaction with the service through interprocess communication.

6. **Service Lifecycle:**

- Three lifecycle methods: `onCreate()`, `onStartCommand()`, and `onDestroy()`.

- Similar to activity lifecycle states.

7. **Creating a Service:**

- Subclass `Service` or use existing subclasses like `IntentService`.

- Implement lifecycle methods (`onCreate()`, `onStartCommand()`, etc.).

8. **Stopping Service:**

- Use `stopSelf()` or `stopService()` to stop the service.

- Differentiate between foreground services and bound services.

9. **Android Rules for Service Management:**

- System stops services to recover resources.

- Priority lowers for long-running services.

- Foreground services have higher priority.

- Services restarted based on return value from `onStartCommand()`.

10. **Manifest Declaration:**

- Declare services in the manifest file.

- Use `<service>` tag with necessary attributes.

- Use explicit intent and no intent-filtering for security.

11. **Intent Service:**

- Subclass of Service for single background thread tasks.

- Implements `onHandleIntent()` method.

- Automatically stops when tasks are completed.

12. **Service Summary:**

- Extend Service class for service creation.

- Implement lifecycle methods and declare services in the manifest.

- Use explicit intent, start and stop service appropriately.

- Ideal for background tasks not requiring user interaction.

Message Broadcasting in Android:

1. **Types of Broadcasting**: Android distinguishes between system broadcasting and custom broadcasting. System broadcasts are sent by the Android system in various situations, while custom broadcasts are sent by apps themselves.

2. **Custom Broadcasting**: Custom broadcasts can be sent in three different ways: normal broadcast, ordered broadcast, or local broadcast. Normal broadcasting sends messages to all registered receivers in parallel, ordered broadcasting delivers messages sequentially, and local broadcasting sends messages within the app.

3. **BroadcastReceiver Class**: `BroadcastReceiver` is used to respond to broadcast announcements in Android. It receives and handles broadcast intents sent by the `sendBroadcast(Intent)` method. `BroadcastReceiver` does not have a UI but can create a status bar notification when a broadcast event occurs.

4. **Steps for Message Broadcasting and Receiving**:

- **Creating a BroadcastReceiver Object**: First, create a `BroadcastReceiver` object to receive messages.

- **BroadcastReceiver Registration**: Register the `BroadcastReceiver` object either dynamically using `registerReceiver()` or statically using the `<receiver>` tag in the manifest file.

- **Using the sendBroadcast Method**: The service can send messages using its `sendBroadcast()` method.

- **Receiving Broadcasted Message**: Implement the `onReceive()` method of the `BroadcastReceiver` class to handle incoming messages. Remember that the `onReceive()` method should perform minimal work and complete within 10 seconds.

5. **Example Implementation**: An example implementation demonstrates how to create a `BroadcastReceiver` object as a private inner class, register it dynamically, send broadcast messages from a service, and receive and handle these messages in an activity.

Android MediaPlayer for streaming radio stations:

1. **App Structure**: The app utilizes the service and `MediaPlayer` component to play live streaming radio stations using URLs. It also employs `BroadcastReceiver` to notify users of events. The `RadioMainActivity` class starts the service, which then handles the MediaPlayer and streaming.

2. **Android Media Player**: Android uses the `MediaPlayer` class to control the playback of audio/video files and streams. It needs to be prepared, started, and released. `prepareAsync()` method is commonly used for streaming to avoid blocking the main thread.

3. **Power Manager and WakeLock**: To keep the CPU running and prevent the screen from dimming or going off during playback, the `PowerManager` and `WakeLock` classes are utilized. `PARTIAL_WAKE_LOCK` is used to keep the CPU running without the screen on.

4. **WifiLock**: `WifiLock` allows the app to keep the Wi-Fi component awake to ensure continuous streaming even when the device screen is off.

5. **Other App Components**: Additional features include progress dialogs during connection attempts, the ability to delete and add radio stations, and resetting the station list.

6. **Stopping and Restarting Service**: The app allows stopping and restarting the service when the user changes the radio station. Communication between activities and the service is demonstrated.

7. **Foreground Service**: Starting from Android 8.0 (API 26), apps are required to use a foreground service to run tasks in the background. `startForegroundService()` method is used to start a service in the foreground, creating a visible notification for the user.

The Usage of `VideoView` for Local and Remote Video Playback

1. **Playback Video Using Implicit Intent and URL**: You can use implicit intents with the action `Intent.ACTION_VIEW` to play remote videos using URLs. This method allows you to provide a media URL, such as a YouTube link, and let the system handle the playback.

2. **Playback Live Streaming Video Using URL and VideoView**: To play local or live stream videos using a URL, you can utilize the `VideoView` class along with the `MediaController` class for control. The `app:layout_constraintDimensionRatio` property is used to maintain the aspect ratio of the video view. Examples of aspect ratios include 4:3 and 16:9.

3. **Playback Embedded Video in Your App**: If the video is embedded within the app, you can parse the file path and pass it to the `setVideoUri()` method. For example, if the video file is saved in the `res/raw` directory, you can construct the Uri accordingly.

4. **Playback Video Outside Your App Directory**: If the video file is located outside your app directory, such as on the device's file system, you need to use methods provided by the environment and external storage directory to access the file. Proper settings permissions in the manifest file are also required to access storage outside of your app directory.