Giới thiệu
Bài viết này hướng dẫn cách tích hợp chức năng tìm kiếm Google vào ứng dụng Android bằng cách sử dụng Intent.ACTION_WEB_SEARCH. Cách này mở trình duyệt hoặc ứng dụng Google Search mặc định của thiết bị với từ khóa do người dùng nhập.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Nhập từ khóa tìm kiếm..."
android:inputType="text" />
<Button
android:id="@+id/btnSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Tìm kiếm Google" />
</LinearLayout>
Bước 3: Viết code tìm kiếm (src/MainActivity.java)
import androidx.appcompat.app.AppCompatActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private Button btnSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
btnSearch = findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(v -> performSearch());
// Optional: Tìm kiếm khi nhấn Enter trên bàn phím
editText.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
});
}
private void performSearch() {
String query = editText.getText().toString().trim();
if (query.isEmpty()) {
editText.setError("Vui lòng nhập từ khóa");
return;
}
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, query);
// Kiểm tra có app nào xử lý intent này không
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
// Fallback: Mở trình duyệt với URL Google Search
String url = "https://www.google.com/search?q=" + Uri.encode(query);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
}
}
Bước 4: Cấu hình Manifest (androidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
</intent-filter>
</activity>
</application>
</manifest>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Nhập từ khóa, nhấn "Tìm kiếm Google" - sẽ mở ứng dụng Google Search hoặc trình duyệt với kết quả tìm kiếm.
Các cách tìm kiếm khác nhau
| Phương pháp | Intent Action | Đặc điểm |
|---|---|---|
| Google Search App | Intent.ACTION_WEB_SEARCH |
Mở app Google Search mặc định, UI đẹp, gợi ý, voice search |
| Trình duyệt web | Intent.ACTION_VIEW + URL Google |
Luôn hoạt động, không cần app Google, UI web |
| Custom Search (Custom Search API) | REST API + JSON | Tùy chỉnh hoàn toàn, hiển thị trong app, cần API key, có hạn mức miễn phí |
| SearchView/Widget | SearchManager + SearchableActivity | Tích hợp vào ActionBar/Toolbar, gợi ý tìm kiếm cục bộ |
Mở rộng: Tìm kiếm trong ứng dụng (Local Search)
// res/xml/searchable.xml
<searchable xmlns:android="https://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint"
android:searchSettingsDescription="@string/search_settings" />
// Manifest
<activity android:name=".SearchResultsActivity">
<intent-filter>
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
// MainActivity - kích hoạt search dialog
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
Lưu ý quan trọng
- Quyền
INTERNETbắt buộc cho fallback mở trình duyệt. ACTION_WEB_SEARCHphụ thuộc vào thiết bị có cài app Google Search (hầu như mọi thiết bị Android đều có).- Luôn kiểm tra
resolveActivity()trước khistartActivity()để tránh crash. - Encode URL đúng cách:
Uri.encode(query)hoặcURLEncoder.encode(query, "UTF-8"). - Để tìm kiếm giọng nói:
RecognizerIntent.ACTION_RECOGNIZE_SPEECH.