Intent.ACTION_WEB_SEARCH:没有后台?

时间:2014-08-29 13:48:54

标签: android android-intent android-activity

我想开始进行网络搜索活动。我不想使用google查询启动浏览器,而是希望使用这种更通用的方法:

Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, query); // query contains search string
startActivity(intent);

但是,令我惊讶的是,后退按钮让我从搜索到主屏幕。而不是应用程序,就像ACTION_VIEW一样。

基本问题:当使用Intent.ACTION_WEB_SEARCH时,如何实现在Backstack上获取当前活动?

1 个答案:

答案 0 :(得分:0)

我有同样的问题。我做了小小的绕行。下面的代码检查您要搜索的文本是否为Web URL。如果是URL-将打开此网站。如果不是URL,它将粘贴到Google搜索框中并显示搜索结果。

此代码已针对API 21+进行了测试

private void searchOnGoogle(String query){
        Uri uri;
            if (Patterns.WEB_URL.matcher(query).matches()) // checks if text is ULR
            {
                uri = Uri.parse(query);
            }
            else {
                uri = Uri.parse("https://www.google.pl/search?q="+query);
            }
            Intent intent = new Intent(ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                            Intent.FLAG_ACTIVITY_CLEAR_TASK |
                            Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                startActivity(intent);
            }
            catch (ActivityNotFoundException e){
                Toast.makeText(getApplicationContext(), getString(R.string.error), Toast.LENGTH_SHORT).show(); // R.string.error - string resource with text you wanna display to user when intent won't run
            }