Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 앱에 구글 검색 기능을 추가하는 방법 (단계별 가이드)

안드로이드 앱에 구글 검색 기능 추가하기

이 예제는 안드로이드 애플리케이션에 구글 검색 기능을 추가하는 방법을 단계별로 보여줍니다. 사용자가 입력한 검색어를 안드로이드의 내장 웹 검색 인텐트(Intent.ACTION_WEB_SEARCH)를 통해 구글 검색으로 연결하는 간단하면서도 실용적인 예제입니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤, 상단 메뉴에서 File → New Project를 선택하여 새 프로젝트를 생성합니다. 프로젝트 생성에 필요한 모든 세부 정보를 입력하고 진행하세요.

2단계: 레이아웃 파일 작성

아래 코드를 res/layout/activity_main.xml 파일에 추가합니다. 검색어를 입력받을 EditText와 검색을 실행할 Button으로 구성된 간단한 수직 레이아웃입니다.

<?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"
    tools:context=".MainActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_centerInParent="true" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnSearch"
        android:text="Search"/>
</LinearLayout>

3단계: MainActivity 자바 코드 작성

다음으로 src/MainActivity.java 파일에 아래 코드를 추가합니다. 버튼 클릭 시 Intent.ACTION_WEB_SEARCH를 사용해 입력된 검색어를 웹 검색 앱으로 전달하는 핵심 로직입니다.

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 {
    EditText editText;
    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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                String term = editText.getText().toString();
                intent.putExtra(SearchManager.QUERY, term);
                startActivity(intent);
            }
        });
    }
}

4단계: 매니페스트 파일 설정

마지막으로 androidManifest.xml 파일에 아래 코드를 추가합니다. 외부 검색 요청을 처리하기 위해 인터넷 권한(INTERNET permission)을 반드시 선언해야 한다는 점에 유의하세요.

<?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>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    </activity>
    </application>
</manifest>

애플리케이션 실행하기

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터와 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 해당 기본 화면에 만든 앱이 표시됩니다.

앱이 정상적으로 실행되면 EditText에 원하는 검색어를 입력하고 Search 버튼을 누릅니다. 그러면 안드로이드가 설치된 검색 앱(기본적으로 구글 검색)이 열리며, 입력한 키워드에 대한 검색 결과를 바로 확인할 수 있습니다.