【问题标题】:Clear chrome browser history programmatically以编程方式清除 chrome 浏览器历史记录
【发布时间】:2016-01-27 11:27:09
【问题描述】:

我尝试使用以下代码,但它不适用于 chrome,只能用于旧浏览器。

Browser.clearHistory(getContentResolver());

【问题讨论】:

  • 请注意,Browser 在 API 级别 23 中已完全删除。
  • @CommonsWare 你知道有什么办法可以和 chrome 浏览器交互吗?
  • Android SDK 本身没有任何内容。我不能说 Chrome 团队是否为他们的 Android 应用记录了任何类型的 API。

标签: android google-chrome android-browser


【解决方案1】:

这段代码对我有用

private void clearHistoryChrome() {
    ContentResolver cr = getContentResolver();
    if (canClearHistory(cr)) {
        deleteHistoryWhere(cr, null);
    }
}

private void deleteHistoryWhere(ContentResolver cr, String whereClause) {
    String CONTENT_URI = "content://com.android.chrome.browser/history";
    Uri URI = Uri.parse(CONTENT_URI);
    Cursor cursor = null;
    try {
        cursor = cr.query(URI, new String[]{"url"}, whereClause,
                null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                final WebIconDatabase iconDb = WebIconDatabase.getInstance();
                do {
                    // Delete favicons
                    // TODO don't release if the URL is bookmarked
                    iconDb.releaseIconForPageUrl(cursor.getString(0));
                } while (cursor.moveToNext());
                cr.delete(URI, whereClause, null);
            }
        }
    } catch (IllegalStateException e) {
        Log.i("DEBUG_", "deleteHistoryWhere IllegalStateException: " + e.getMessage());
        return;
    } finally {
        if (cursor != null) cursor.close();
    }
    Log.i("DEBUG_", "deleteHistoryWhere: GOOD");
}

public boolean canClearHistory(ContentResolver cr) {
    String CONTENT_URI = "content://com.android.chrome.browser/history";
    Uri URI = Uri.parse(CONTENT_URI);
    String _ID = "_id";
    String VISITS = "visits";
    Cursor cursor = null;
    boolean ret = false;
    try {
        cursor = cr.query(URI,
                new String[]{_ID, VISITS},
                null, null, null);
        if (cursor != null) {
            ret = cursor.getCount() > 0;
        }
    } catch (IllegalStateException e) {
        Log.i("DEBUG_", "canClearHistory IllegalStateException: " + e.getMessage());
    } finally {
        if (cursor != null) cursor.close();
    }
    Log.i("DEBUG_", "canClearHistory: " + ret);
    return ret;
}

我想这会对你有所帮助

【讨论】:

  • canClearHistory 日志值为 false 我该怎么办?
  • Log.i("DEBUG_", "canClearHistory:" + ret);返回 ret;
猜你喜欢
  • 2011-04-16
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 2011-11-14
  • 1970-01-01
  • 2015-05-25
相关资源
最近更新 更多