HarmonyOS技术社区 · 2021年04月20日

002 使用鸿蒙WebView创建简单浏览器 step 2

通过DataAbility给简易浏览器增加历史记录存储

学习鸿蒙的点滴记录在Gitee上面:gitee.com/javaaier/Ha…

  • 注:本次笔记及代码中使用了发发老师(钟洪发)视频的配套代码.侵删.
  1. 添加数据库类
@Database(entities = {WebViewHistory.class, WebViewFavorite.class}, version = 1)
public abstract class WebViewStore extends OrmDatabase {
}
  • 添加历史记录类
@Entity(tableName = "WebViewHistory",
        indices = {@Index(value = {"historyId"}, name = "historyId_index", unique = true)})
public class WebViewHistory extends OrmObject{
    @PrimaryKey(autoGenerate = true)
    private Integer historyId;
    private Long browseTime;
    private String url;
    private String title;
    ... 省略了 getters setters toString方法
}
  • 添加Data Ability,并实现增加和查询的方法
public class WebViewHistoryAbility extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    private OrmContext ormContext = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        HiLog.info(LABEL_LOG, "WebViewHistoryAbility onStart");
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        ormContext = databaseHelper.getOrmContext("WebViewStore", "WebViewStore.db", WebViewStore.class, null);
    }

    @Override
    public ResultSet query(Uri uri, String[] columns, DataAbilityPredicates predicates) {
        HiLog.info(LABEL_LOG, "WebViewHistoryAbility query");
        if (ormContext == null) {
            return null;
        }
        System.out.println("----------------------------开始获取数据--------------------------");
        //真正查询数据的语句
        OrmPredicates ormPredicates = DataAbilityUtils.createOrmPredicates(predicates, WebViewHistory.class);
        ResultSet rs = ormContext.query(ormPredicates, columns);
        return rs;
    }

    @Override
    public int insert(Uri uri, ValuesBucket value) {
        HiLog.info(LABEL_LOG, "WebViewHistoryAbility insert");
        if (ormContext == null) {
            return -1;
        }
        System.out.println("----------------------------开始写入数据--------------------------");
        WebViewHistory history = new WebViewHistory();
        history.setBrowseTime(value.getLong("browseTime"));
        history.setTitle(value.getString("title"));
        history.setUrl(value.getString("url"));
        boolean insert = ormContext.insert(history);
        if (!insert) {
            return -1;
        }
        boolean flush = ormContext.flush();
        if (!flush) {
            return -1;
        }
        int id = Math.toIntExact(history.getRowId());
        System.out.println("----------------------------写入数据完成--------------------------");
        return id;

    }
  • 在config.json文件中添加权限
  "reqPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.GET_DISTRIBUTED_DEVICE_INFO"
      },
      {
        "name": "ohos.permission.DISTRIBUTED_DATASYNC"
      },
      {
        "name": "ohos.permission.READ_USER_STORAGE"
      },
      {
        "name": "com.javaaier.family.huawei.DataAbilityShellProvider.PROVIDER"
      }
    ],
    "defPermissions": [
      {
        "name": "com.javaaier.family.huawei.DataAbilityShellProvider.PROVIDER",
        "grantMode": "system_grant"
      }
    ]
  • 修改WebView界面,增加查看历史记录的按钮(本次笔记只记录输出历史记录到控制台)
//定义历史记录Data Ability的Uri
historyUri = Uri.parse("dataability:///com.javaaier.family.huawei.WebViewHistoryAbility");


//新增历史记录
   ValuesBucket values = new ValuesBucket();
                values.putLong("browseTime", System.currentTimeMillis());
                values.putString("url", "url");
                values.putString("title", webView.getTitle());
                try {
                    int insertRowId = helper.insert(historyUri, values);
                } catch (DataAbilityRemoteException e) {
                    e.printStackTrace();
                }

//    查看历史记录
  case ResourceTable.Id_button_webView_viewHistory: {
                    try {
                        DataAbilityPredicates dap = new DataAbilityPredicates();
                        dap.orderByDesc("browseTime");
                        ResultSet rs = helper.query(historyUri,
                                new String[]{"historyId", "browseTime", "url", "title"},
                                dap);
                        Utils.showTip(SimpleWebViewAbilitySlice.this, "已读取数据");
                        if (rs.getRowCount() > 0) {
                            rs.goToFirstRow();
                            for (int i = 0; i < rs.getRowCount(); i++) {
                                System.out.println("查询出来的数据:"
                                        + rs.getInt(rs.getColumnIndexForName("historyId")) + "," +
                                        rs.getLong(rs.getColumnIndexForName("browseTime")) + "," +
                                        rs.getString(rs.getColumnIndexForName("url")) + "," +
                                        rs.getString(rs.getColumnIndexForName("title")));
                                rs.goToNextRow();
                            }
                        }
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    }
                }
  • 运行及验证是否正确
    最终记录和读取的历史记录如下图所示:

作者:人工智能姬
想了解更多内容,请访问51CTO和华为合作共建的鸿蒙社区:https://harmonyos.51cto.com

21_9.jpg

推荐阅读
关注数
2960
内容数
446
华为鸿蒙相关技术,活动及资讯,欢迎关注及加入创作
目录
极术微信服务号
关注极术微信号
实时接收点赞提醒和评论通知
安谋科技学堂公众号
关注安谋科技学堂
实时获取安谋科技及 Arm 教学资源
安谋科技招聘公众号
关注安谋科技招聘
实时获取安谋科技中国职位信息