Start Google search query from activity - Android

后端 未结 5 1581
情书的邮戳
情书的邮戳 2020-12-14 08:42

I was wondering if there is an easier way (or any way) to start a Browser with a Google search query. For example user can select a certain word or phrase and click a button

相关标签:
5条回答
  • 2020-12-14 09:02

    You can do this quite easily with a few lines of code (assuming you want to search Google for 'fish'):

    String escapedQuery = URLEncoder.encode(query, "UTF-8");
    Uri uri = Uri.parse("http://www.google.com/#q=" + escapedQuery);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
    

    Otherwise, if you would rather start up your own Activity to handle the browsing, you should be able to do so with a WebView: http://developer.android.com/reference/android/webkit/WebView.html

    I think the better answer here is @zen_of_kermit's. It would be nice though, if Android allowed a user to provide the Search engine has an extra though for the ACTION_WEB_SEARCH, rather than just using Google.

    0 讨论(0)
  • 2020-12-14 09:07

    I recently tried this. This appears to work fine. If any modifications to be done let me know as I am new to android development.

    mEdit   = (EditText)findViewById(R.id.editText);
    

    in your click view,

    String q = mEdit.getText().toString();
                            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
                            intent.putExtra(SearchManager.QUERY, q);
                            startActivity(intent);
    
    0 讨论(0)
  • 2020-12-14 09:17

    The Intent class defines an action specifically for web searches:

    http://developer.android.com/reference/android/content/Intent.html#ACTION_WEB_SEARCH

    Here's an example of how to use it:

    Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
    intent.putExtra(SearchManager.QUERY, query); // query contains search string
    startActivity(intent);
    
    0 讨论(0)
  • 2020-12-14 09:21

    the # gave me trouble:

    Uri uri = Uri.parse("https://www.google.com/search?q="+query);
    Intent gSearchIntent = new Intent(Intent.ACTION_VIEW, uri);
    activity.startActivity(gSearchIntent);
    
    0 讨论(0)
  • 2020-12-14 09:26
                    String Search= null;
                    try {
                        Search= URLEncoder.encode(s, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    Uri uri = Uri.parse("http://www.google.com/#q=" + Search);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
            });
    
    0 讨论(0)
提交回复
热议问题