🌟【干货预警】鸿蒙开发宝藏案例大揭秘!手把手教你玩转常用功能🌟
大家好呀~我是你们的老朋友[你的名字],今天在扒拉鸿蒙文档的时候,突然发现官方竟然藏了一堆超实用的开发案例!😱 之前总觉得鸿蒙生态资料少,结果这些案例简直就是“新手村外挂”啊!立马熬夜整理了一波,全是真实开发中高频用到的功能,附带代码+讲解,看完直接起飞!🛫
📱 案例一:3 行代码实现页面跳转(带参数)
场景:点击按钮跳转到详情页,并传递用户 ID
// 当前页面按钮点击事件 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); // 传递参数 startAbility(intent); });
复制代码
避坑指南:
DeviceId留空表示当前设备
必须在config.json中提前注册DetailAbility路由,否则闪退!
参数支持 String、int 等基本类型,复杂数据需用序列化
🔄 案例二:列表数据动态渲染(含下拉刷新)
痛点:官方文档只讲基础 ListContainer,但实际开发必加下拉刷新!
// 1. 布局中添加RefreshContainer组件 RefreshContainer refreshContainer = findComponentById(ResourceTable.Id_refresh_container); ListContainer listContainer = new ListContainer(context); refreshContainer.addComponent(listContainer);
// 2. 设置下拉监听 refreshContainer.setRefreshListener(new RefreshListener() { @Override public void onRefreshing() { // 模拟网络请求 getNewDataFromNetwork(); refreshContainer.finishRefresh(); // 停止动画 } });
// 3. 数据绑定(使用DataAbilityHelper操作数据库) // ... 详见官方Sample中的TodoList案例
复制代码
性能优化:
复用 Item 组件避免内存抖动
分页加载时在onScrollEnd事件追加数据
🌐 案例三:网络请求封装(Retrofit 风格)
为什么要封装:官方 HttpTask 写回调太反人类!
// 自定义网络工具类 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); } // 处理失败、超时... }); task.execute(); } }
// 调用示例(获取天气数据) HttpUtils.get("https://api.weather.com", new HttpCallback() { @Override public void onSuccess(String data) { // 更新UI } });
复制代码
高阶技巧:
🗄️ 案例四:数据持久化(轻量级存储)
替代 SharedPreferences:鸿蒙的 Preferences 更香!
// 存数据 Preferences preferences = new Preferences(this); preferences.putString("username", "鸿蒙小王子"); preferences.flush(); // 立即写入
// 取数据(异步回调保证性能) preferences.getString("username", "default", new PreferencesCallback() { @Override public void onSuccess(String value) { // 显示用户名 } });
复制代码
适用场景:
🔧 案例五:调用系统能力(拨打电话、GPS 等)
权限申请是重点:
// 1. 声明权限:config.json中添加 "reqPermissions": [ { "name": "ohos.permission.PLACE_CALL" } ]
// 2. 动态申请(重点!!) if (verifySelfPermission("ohos.permission.PLACE_CALL") != 0) { requestPermissionsFromUser(new String[]{"ohos.permission.PLACE_CALL"}, 1); } else { makeCall(); }
// 3. 拨打电话 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); }
复制代码
常见坑点:
忘记动态申请直接调用会闪退
URI 格式必须严格遵循tel:前缀
🎯 结语
其实鸿蒙文档里还藏着很多“骚操作”,比如分布式任务调度、跨设备流转这些黑科技。
刚入门的小伙伴可能会觉得文档晦涩,但多踩几次坑就会发现:真香!🤣 遇到问题欢迎留言,咱们一起交流成长!最后送上鸿蒙圣经——“多看 Sample,少写 Bug”,下期见!
👉 互动话题:你开发鸿蒙时踩过最深的坑是啥?评论区吐槽!
评论