在Android应用中实现Google搜索的例子

有一个很简单的方法在你的 Android 应用中实现 Google 搜索。在这个例子中,我们将接受用户的输入作为搜索词,我们将使用到 Intent.ACTION_WEB_SEARCH 。

GoogleSearchIntentActivity.java

package com.technotalkative.googlesearchintent;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class GoogleSearchIntentActivity extends Activity {

 private EditText editTextInput;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        editTextInput = (EditText) findViewById(R.id.editTextInput);
   }

    public void onSearchClick(View v)
    {
     try {
       Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
             String term = editTextInput.getText().toString();
             intent.putExtra(SearchManager.QUERY, term);
             startActivity(intent);
  } catch (Exception e) {
   // TODO: handle exception
  }

    }
}

main.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="10dp">

    <edittext android:id="@+id/editTextInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter search text">

        <requestfocus>
    </requestfocus></edittext>

    <button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Search" android:layout_gravity="center" android:onclick="onSearchClick" android:layout_margintop="10dp">

</button></linearlayout>

注意:不要忘了在 AndroidManifest.xml 文件中添加 INTERNET 权限。

 <uses-permission android:name="android.permission.INTERNET">
</uses-permission>

输出:

Android - Google search intent

原文地址:https://www.cnblogs.com/xiaochao1234/p/3754994.html