Jetpack Compose安卓穿戴应用跨启动数据持久化实现咨询
1. Persist and Restore Score Data
Since you're using Java and ViewModel, the simplest way to persist small score data is using SharedPreferences. This aligns with the persistence pattern used in the sample Wear stopwatch app you referenced. Here's a step-by-step implementation:
a. Create a Persistence Helper Class
This class wraps SharedPreferences to handle saving/loading scores cleanly:
import android.content.Context; import android.content.SharedPreferences; public class ScorePersistenceHelper { private static final String PREFS_NAME = "RefScoreKeeperPrefs"; private static final String KEY_TEAM_A = "team_a_score"; private static final String KEY_TEAM_B = "team_b_score"; private final SharedPreferences prefs; public ScorePersistenceHelper(Context context) { prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); } // Save current scores to device storage public void saveScores(int teamA, int teamB) { SharedPreferences.Editor editor = prefs.edit(); editor.putInt(KEY_TEAM_A, teamA); editor.putInt(KEY_TEAM_B, teamB); editor.apply(); // Async save (use commit() only if immediate confirmation is needed) } // Load saved scores (defaults to 0 if no data exists) public int getTeamAScore() { return prefs.getInt(KEY_TEAM_A, 0); } public int getTeamBScore() { return prefs.getInt(KEY_TEAM_B, 0); } // Optional: Clear saved data for a new game public void clearScores() { prefs.edit().clear().apply(); } }
b. Integrate with ViewModel and Activity
Update your ViewModel to accept loaded scores, and handle persistence in your Activity lifecycle methods:
ViewModel (Java):
import androidx.lifecycle.ViewModel; public class ScoreViewModel extends ViewModel { private int teamAScore = 0; private int teamBScore = 0; public int getTeamAScore() { return teamAScore; } public void setTeamAScore(int score) { teamAScore = score; } public int getTeamBScore() { return teamBScore; } public void setTeamBScore(int score) { teamBScore = score; } // Update ViewModel state with saved data public void loadSavedScores(int savedA, int savedB) { teamAScore = savedA; teamBScore = savedB; } }
Activity (Java):
import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; import android.os.Bundle; public class ScoreActivity extends AppCompatActivity { private ScoreViewModel scoreViewModel; private ScorePersistenceHelper persistenceHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize ViewModel and persistence helper scoreViewModel = new ViewModelProvider(this).get(ScoreViewModel.class); persistenceHelper = new ScorePersistenceHelper(this); } @Override protected void onResume() { super.onResume(); // Restore saved scores into ViewModel when app opens/resumes int savedA = persistenceHelper.getTeamAScore(); int savedB = persistenceHelper.getTeamBScore(); scoreViewModel.loadSavedScores(savedA, savedB); // Refresh UI with restored data updateScoreUI(); } @Override protected void onPause() { super.onPause(); // Save scores whenever the app moves to background (covers swipe dismiss and system kills) persistenceHelper.saveScores(scoreViewModel.getTeamAScore(), scoreViewModel.getTeamBScore()); } // Helper method to update UI with ViewModel data private void updateScoreUI() { // Replace with your actual UI logic (e.g., setText on score TextViews) // For Jetpack Compose, observe ViewModel state in your composable to trigger recomposition } }
Key note: Using onPause instead of just onDestroy ensures data is saved even if the system kills the app in the background, not just when swiped away. This matches the reliable persistence behavior of the sample app.
2. Handling Swipe to Dismiss
Disabling the swipe-to-dismiss gesture on Wear OS is generally discouraged, as it breaks platform-wide user expectations. However, if you need to prevent accidental dismissals, you can use the Wearable library:
- Add the Wearable dependency to your app-level
build.gradle(module level):
implementation 'com.google.android.support:wearable:2.8.1'
- Extend
WearableActivityinstead ofAppCompatActivityand disable swipe dismissal:
import com.google.android.wearable.activity.WearableActivity; public class ScoreActivity extends WearableActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Disable swipe to dismiss gesture setSwipeToDismissEnabled(false); // Rest of your initialization code... } }
Keep in mind this may not be supported on all Wear OS versions, and Google recommends relying on persistence to restore data rather than blocking standard user gestures.
内容的提问来源于stack exchange,提问作者Colonel Mustard

