0

I need the following logic: when I click a button, google search string opens up, like this
I have the following in MainActivity:

        val mainBtn = findViewById<Button>(R.id.main_btn)

        mainBtn.setOnClickListener {
            val intent = Intent(Intent.ACTION_WEB_SEARCH)
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            } else {
                Toast.makeText(this, "Sorry, no such app", Toast.LENGTH_SHORT).show()
            }
        }

and the following in Manifest file:

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.WEB_SEARCH"/>
                <category android:name="android.intent.category.LAUNCHER"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="text/plain"/>
            </intent-filter>
        </activity>

Thank you in advance for any help

  • https://developer.android.com/reference/android/content/Intent#ACTION_WEB_SEARCH – CTD Apr 25 '22 at 08:40

1 Answers1

0

You should add some search query to the intent, it won't work without it.

intent.putExtra(SearchManager.QUERY, "some query")

If the intent.resolveActivity(packageManager) returns null try to add the queries block to your AndroidManifest before or after the application (look here):

<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
    </intent>
</queries>
Stepan Kulagin
  • 465
  • 3
  • 8
  • I added your line of code to mine right after the string `val intent = Intent(Intent.ACTION_WEB_SEARCH)` But still does not work, I get a toast message from the Else block – Daniyar Amirov Apr 25 '22 at 09:08
  • solved the problem by adding Avitals code in MainActivity instead of my verification from the link you provided, now a google search string opens up with default query, but I would like to make as it is shown in my gif, other options I have not found yet – Daniyar Amirov Apr 25 '22 at 10:26
  • On API 32 it works almost like in your gif without default query, but on API 30 doesn't. – Stepan Kulagin Apr 25 '22 at 11:00