To customize your app's view using Material Design 3 components and meet your requirements, you'll need to make several changes to your current code, primarily in your activity_main.xml layout and your MainActivity.java code. Below, I'll guide you through the steps to achieve the following:
- Use Material Design 3 components.
- Implement a
MaterialCardView for the current activity.
- Add a start/stop button in the card's header.
- Display the last 4 recognized activities within the card (with the last line showing the current activity).
1. Update Gradle Dependencies
First, ensure that you have the necessary dependencies for Material Design Components. In your app-level build.gradle file, add the following dependency (if you haven't already):
dependencies {
// Material Design Components
implementation 'com.google.android.material:material:1.9.0'
}
Note: As of my knowledge cutoff in September 2021, the latest version was 1.5.0. Please check for the latest version here and adjust accordingly.
2. Update Your Theme to Material 3
In your styles.xml, set your app's theme to use Material 3:
<!-- Base application theme. -->
<style name="Theme.YourApp" parent="Theme.Material3.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
3. Modify activity_main.xml
Replace your current activity_main.xml content with the following code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- AppBarLayout with a Toolbar (Optional) -->
<!-- Uncomment if you want to add a toolbar
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="Activity Recognition"
app:titleTextColor="@android:color/white"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</com.google.android.material.appbar.AppBarLayout>
-->
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<com.google.android.material.card.MaterialCardView
android:id="@+id/activityCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="8dp"
app:cardElevation="4dp"
app:strokeColor="@color/black"
app:strokeWidth="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Card Header with Start/Stop Button -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="8dp">
<TextView
android:id="@+id/cardTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Activity Recognition"
android:textAppearance="?attr/textAppearanceHeadline6" />
<com.google.android.material.button.MaterialButton
android:id="@+id/startStopButton"
style="@style/Widget.Material3.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
app:icon="@drawable/ic_play_arrow"
app:iconGravity="textStart" />
</LinearLayout>
<!-- Divider -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/divider" />
<!-- Activity List -->
<LinearLayout
android:id="@+id/activityListLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<!-- Initially empty; will be populated dynamically -->
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Explanation:
- We've added a
MaterialCardView to contain the activity information.
- Inside the card, there's a header (
LinearLayout) with a title and a start/stop button.
- The
activityListLayout is a LinearLayout where we'll dynamically add the last 4 recognized activities.
- We're using
MaterialButton for the start/stop button.
- Note that colors like
@color/black and @color/divider should be defined in your colors.xml. You can adjust these as needed.
4. Update Icons and Colors
Add required icons to your drawable folder.
- For the start icon (
ic_play_arrow) and stop icon (ic_stop), you can use vector assets from Android Studio's built-in icon library.
- Right-click on the
drawable folder -> New -> Vector Asset -> Select the appropriate icons.
Define any custom colors in your colors.xml if needed.
5. Update MainActivity.java
Now, modify your MainActivity to handle the new UI components and display the activity list.
Here's how you can update your MainActivity:
public class MainActivity extends AppCompatActivity {
private static final int ACTIVITY_RECOGNITION_REQUEST_CODE = 100;
private MaterialButton startStopButton;
private LinearLayout activityListLayout;
private boolean isServiceRunning = false;
private BroadcastReceiver transitionBroadcastReceiver;
private DatabaseHelper databaseHelper;
private static final int MAX_ACTIVITIES = 4; // Maximum number of activities to display
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize database helper
DatabaseHelper.initializeInstance(this);
databaseHelper = DatabaseHelper.getInstance();
startStopButton = findViewById(R.id.startStopButton);
activityListLayout = findViewById(R.id.activityListLayout);
// Request permission if not granted
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACTIVITY_RECOGNITION},
ACTIVITY_RECOGNITION_REQUEST_CODE);
}
startStopButton.setOnClickListener(v -> {
if (isServiceRunning) {
stopActivityRecognitionService();
} else {
startActivityRecognitionService();
}
});
// Load previous activities from database (optional)
loadPreviousActivities();
}
private void startActivityRecognitionService() {
Intent serviceIntent = new Intent(this, ActivityTransitionService.class);
ContextCompat.startForegroundService(this, serviceIntent);
// Register receiver to update UI
transitionBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String activityInfo = intent.getStringExtra("activity");
updateActivityList(activityInfo);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(transitionBroadcastReceiver,
new IntentFilter("TRANSITION_ACTION"));
Toast.makeText(this, "Started activity recognition service", Toast.LENGTH_SHORT).show();
isServiceRunning = true;
startStopButton.setText("Stop");
startStopButton.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_stop));
requestIgnoreBatteryOptimizations();
}
private void stopActivityRecognitionService() {
Intent serviceIntent = new Intent(this, ActivityTransitionService.class);
stopService(serviceIntent);
if (transitionBroadcastReceiver != null) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(transitionBroadcastReceiver);
transitionBroadcastReceiver = null;
}
Toast.makeText(this, "Stopped activity recognition service", Toast.LENGTH_SHORT).show();
isServiceRunning = false;
startStopButton.setText("Start");
startStopButton.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_play_arrow));
}
private void updateActivityList(String activityInfo) {
// Add the new activity to the database
databaseHelper.insertTransitionEvent(System.currentTimeMillis(), activityInfo, "Transition");
// Reload the activity list
loadPreviousActivities();
}
private void loadPreviousActivities() {
// Clear current views
activityListLayout.removeAllViews();
// Get the last 4 activities from the database
List<String> recentActivities = databaseHelper.getLastNActivities(MAX_ACTIVITIES);
// If there are no activities, display a message
if (recentActivities.isEmpty()) {
TextView noDataTextView = new TextView(this);
noDataTextView.setText("No activities recorded yet.");
noDataTextView.setPadding(8, 8, 8, 8);
activityListLayout.addView(noDataTextView);
return;
}
// Display the activities
for (int i = 0; i < recentActivities.size(); i++) {
String activity = recentActivities.get(i);
TextView activityTextView = new TextView(this);
activityTextView.setText(activity);
activityTextView.setPadding(8, 8, 8, 8);
// Highlight the last activity (current activity)
if (i == recentActivities.size() - 1) {
activityTextView.setTypeface(null, Typeface.BOLD);
}
activityListLayout.addView(activityTextView);
}
}
private void requestIgnoreBatteryOptimizations() {
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
String packageName = getPackageName();
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(android.net.Uri.parse("package:" + packageName));
startActivity(intent);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == ACTIVITY_RECOGNITION_REQUEST_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
// You can choose to start the service automatically here
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
protected void onDestroy() {
stopActivityRecognitionService();
super.onDestroy();
}
}
Notes on MainActivity Changes:
- Added a
startStopButton to toggle the activity recognition service.
- Used an
isServiceRunning boolean to track the state of the service.
- Updated the
startActivityRecognitionService() and stopActivityRecognitionService() methods to update the button text and icon accordingly.
- Implemented
updateActivityList() method to update the UI with the new activity.
- Implemented
loadPreviousActivities() method to load the last 4 activities from the database.
- Used a
MAX_ACTIVITIES constant to limit the number of displayed activities to 4.
6. Update DatabaseHelper.java
Add a method to retrieve the last N activities:
public class DatabaseHelper extends SQLiteOpenHelper {
// ... existing code ...
// Method to get the last N activities
public List<String> getLastNActivities(int n) {
List<String> activities = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT " + COLUMN_ACTIVITY + ", " + COLUMN_TIMESTAMP + " FROM " + TABLE_TRANSITIONS +
" ORDER BY " + COLUMN_TIMESTAMP + " DESC LIMIT " + n;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
String activity = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_ACTIVITY));
long timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_TIMESTAMP));
String formattedTime = DateFormat.getDateTimeInstance().format(new Date(timestamp));
activities.add(formattedTime + " - " + activity);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
Collections.reverse(activities); // So the oldest activity comes first
return activities;
}
// ... existing code ...
}
Explanation:
- Added
getLastNActivities(int n) method to retrieve the last n activities from the database.
- The method orders the results by
timestamp in descending order and limits the results to n.
- Each activity is stored with its timestamp formatted for display.
7. Handling Activities in ActivityTransitionService
Ensure that your ActivityTransitionService is broadcasting the activity info correctly so that MainActivity can receive and display it.
8. Icons and Styling
Make sure to adjust the icons and styles to match your preferences.
- Use appropriate icons for start (
ic_play_arrow) and stop (ic_stop) in the drawable folder.
- Adjust colors, text sizes, and padding as needed in your XML layouts and styles.
9. Testing
Test your app thoroughly:
- Start the activity recognition service and verify that activities are being recorded and displayed.
- Check that the start/stop button toggles the service correctly.
- Verify that only the last 4 activities are displayed and that the current activity is highlighted.
Additional Tips
- Error Handling: Add error handling as needed to manage cases where the database may not return any activities or if there are issues with the activity recognition.
- Optimization: Consider using a
RecyclerView instead of dynamically adding TextViews to a LinearLayout if you expect the list to grow in the future.
- Material Design Guidelines: Follow the Material Design Guidelines to ensure consistency and accessibility in your app.
Conclusion
By making these changes, your app will now:
- Use Material Design 3 components.
- Display a card with a header that includes a start/stop button.
- Show the last 4 recognized activities, with the last line displaying the current activity.
Feel free to adjust the layout, styles, and code to better fit your specific needs or preferences.