DEV Community

ι™ˆζ¨
ι™ˆζ¨

Posted on

Treasure Case Sharing of HarmonyOS 5 Development β€” Seamless Multi-Screen Interaction with Drag-and-Drop

🌟[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);  
});
Enter fullscreen mode Exit fullscreen mode

Pitfall Guide:

  1. Leaving DeviceId empty means the current device
  2. You must register the DetailAbility route in config.json in advance, or the app will crash!
  3. 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
Enter fullscreen mode Exit fullscreen mode

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  
    }  
});
Enter fullscreen mode Exit fullscreen mode

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  
    }  
});
Enter fullscreen mode Exit fullscreen mode

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);  
}
Enter fullscreen mode Exit fullscreen mode

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)