以编程方式清除Chrome浏览器历史记录

3
我尝试使用以下代码,但它不能在Chrome上工作,只能在旧浏览器上运行。
Browser.clearHistory(getContentResolver());

3
请注意,API Level 23 中完全取消了 Browser - CommonsWare
@CommonsWare 你知道是否有与 Chrome 浏览器交互的方式吗? - SPatrickApps
2
Android SDK本身没有任何东西。至于Chrome团队是否为其Android应用程序记录了任何类型的API,我无法确定。 - CommonsWare
1个回答

3
这段代码对我有用。
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;
}

我认为这会对你有所帮助。

可以清除历史记录,但是日志值为false,我该怎么办? - Makvin
Log.i("DEBUG_", "canClearHistory: " + ret); return ret; - Makvin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接