π[Dry Goods Alert] HarmonyOS Development Treasure Case Revealed! Hands-on Guide to Mastering Common Featuresπ
Hello everyone~ I'm your old friend [Your Name]. While browsing the HarmonyOS documentation today, I suddenly discovered that the official docs actually hide a bunch of super practical development cases! π± I used to think there were few resources in the HarmonyOS ecosystem, but these cases are simply "cheat codes for beginners"! I immediately stayed up late to organize themβall are high-frequency features used in real development, with code + explanations. After reading, you'll level up instantly! π«
π± Case 1: Page Navigation with Parameters in 3 Lines of Code
Scenario: Click a button to jump to the details page and pass a user ID
// Button click event on the current page
Button button = findComponentById(ResourceTable.Id_btn_jump);
button.setClickedListener(component -> {
Intent intent = new Intent();
Operation operation = new Intent.OperationBuilder()
.withDeviceId("")
.withBundleName("com.example.demo")
.withAbilityName("DetailAbility")
.build();
intent.setOperation(operation);
intent.setParam("user_id", 1001); // Pass parameter
startAbility(intent);
});
Pitfall Guide:
- Leaving
DeviceId
empty means the current device - You must register the
DetailAbility
route inconfig.json
in advance, or the app will crash! - Parameters support basic types like String, int; for complex data, use serialization
π Case 2: Dynamic List Rendering (with Pull-to-Refresh)
Pain Point: The official docs only cover basic ListContainer, but in real development, pull-to-refresh is a must!
// 1. Add RefreshContainer component in layout
RefreshContainer refreshContainer = findComponentById(ResourceTable.Id_refresh_container);
ListContainer listContainer = new ListContainer(context);
refreshContainer.addComponent(listContainer);
// 2. Set pull-to-refresh listener
refreshContainer.setRefreshListener(new RefreshListener() {
@Override
public void onRefreshing() {
// Simulate network request
getNewDataFromNetwork();
refreshContainer.finishRefresh(); // Stop animation
}
});
// 3. Data binding (use DataAbilityHelper to operate database)
// ... See the official Sample's TodoList case for details
Performance Optimization:
- Reuse Item components to avoid memory jitter
- For pagination, append data in the
onScrollEnd
event
π Case 3: Network Request Encapsulation (Retrofit Style)
Why encapsulate: The official HttpTask callback style is too unfriendly!
// Custom network utility class
public class HttpUtils {
public static void get(String url, HttpCallback callback) {
HttpTask task = new HttpTask(url, new HttpRequestCallback() {
@Override
public void onSuccess(HttpResponse response) {
String result = response.getResult();
callback.onSuccess(result);
}
// Handle failure, timeout...
});
task.execute();
}
}
// Usage example (get weather data)
HttpUtils.get("https://api.weather.com", new HttpCallback() {
@Override
public void onSuccess(String data) {
// Update UI
}
});
Advanced Tips:
- Use Gson to parse JSON data
- Use
EventHandler
to update UI from child threads
ποΈ Case 4: Data Persistence (Lightweight Storage)
Better than SharedPreferences: HarmonyOS Preferences is even better!
// Store data
Preferences preferences = new Preferences(this);
preferences.putString("username", "HarmonyOS Prince");
preferences.flush(); // Write immediately
// Retrieve data (asynchronous callback for performance)
preferences.getString("username", "default", new PreferencesCallback() {
@Override
public void onSuccess(String value) {
// Display username
}
});
Applicable Scenarios:
- User login status
- App personalization settings
π§ Case 5: Calling System Capabilities (Phone Call, GPS, etc.)
Permission application is key:
// 1. Declare permission: add in config.json
"reqPermissions": [
{ "name": "ohos.permission.PLACE_CALL" }
]
// 2. Dynamic request (important!!)
if (verifySelfPermission("ohos.permission.PLACE_CALL") != 0) {
requestPermissionsFromUser(new String[]{"ohos.permission.PLACE_CALL"}, 1);
} else {
makeCall();
}
// 3. Make a call
private void makeCall() {
Intent intent = new Intent();
Operation operation = new Intent.OperationBuilder()
.withAction("ohos.intent.action.DIAL")
.withUri("tel:13800138000")
.build();
intent.setOperation(operation);
startAbility(intent);
}
Common Pitfalls:
- Forgetting to request permission dynamically before calling will cause a crash
- URI format must strictly follow the
tel:
prefix
π― Conclusion
Actually, there are many more "cool tricks" hidden in the HarmonyOS docs, such as distributed task scheduling and cross-device flowβthese are cutting-edge features.
Beginners may find the docs obscure at first, but after a few stumbles, you'll realize: it's awesome! π€£ If you run into problems, feel free to commentβlet's learn and grow together! Finally, here's the HarmonyOS Bibleβ"Read more Samples, write fewer Bugs". See you next time!
π Discussion Topic: What's the biggest pitfall you've encountered in HarmonyOS development? Share your stories in the comments!
Top comments (0)