เริ่มใช้งาน

เอกสารนี้อธิบายวิธีเริ่มพัฒนาด้วย Awareness API ใน Android Awareness API เป็นส่วนหนึ่งของบริการ Google Play

คุณต้องมีบัญชี Google จึงจะใช้ Awareness API ได้ หากมีบัญชีอยู่แล้ว ทุกอย่างก็พร้อมใช้งานแล้ว คุณอาจต้องใช้บัญชี Google แยกต่างหากเพื่อวัตถุประสงค์ในการทดสอบด้วย

ก่อนเริ่มต้น

รับคีย์ API

หากยังไม่ได้เปิดใช้ Awareness API และรับคีย์ Google API ให้ทําตามขั้นตอนในการลงชื่อสมัครใช้และคีย์ API

กำหนดค่าแอป

  1. ในไฟล์ build.gradle ระดับโปรเจ็กต์ ให้ใส่ที่เก็บ Maven ของ Google ทั้งในส่วน buildscript และ allprojects ดังนี้

    buildscript {
        repositories {
            google()
        }
    }
    
    allprojects {
        repositories {
            google()
        }
    }
    
  2. เพิ่ม Dependency สําหรับ Awareness API ลงในไฟล์ Gradle ระดับแอปของโมดูล ซึ่งโดยปกติจะเป็น app/build.gradle

    dependencies {
      implementation 'com.google.android.gms:play-services-awareness:19.1.0'
    }
    
  3. เพิ่มคีย์ Awareness API ลงในไฟล์ AndroidManifest.xml ของแอป โดยเพิ่มแท็ก <meta-data> ที่มี android:name="com.google.android.awareness.API_KEY" สําหรับ android:value ให้ใส่คีย์ Awareness API ของคุณเองโดยใส่เครื่องหมายคําพูดคร่อมไว้

    <manifest>
        <application>
            <meta-data
                android:name="com.google.android.awareness.API_KEY"
                android:value="API_KEY"/>
        </application>
    </manifest>
  4. เพิ่มสิทธิ์ที่จําเป็นลงในไฟล์ AndroidManifest.xml ของแอป สิทธิ์ที่จําเป็นจะแตกต่างกันไป โดยขึ้นอยู่กับเมธอด API และประเภทรั้วที่แอปของคุณใช้

ตัวอย่างการเรียกใช้

ตัวอย่างการเรียกใช้ getDetectedActivity() ต่อไปนี้แสดงวิธีใช้รูปแบบบริการ Google Play แบบไม่เชื่อมต่อกับ Awareness API

    // Each type of contextual information in the snapshot API has a corresponding "get" method.
    // For instance, this is how to get the user's current Activity.
    Awareness.getSnapshotClient(this).getDetectedActivity()
        .addOnSuccessListener(new OnSuccessListener<DetectedActivityResponse>() {
            @Override
            public void onSuccess(DetectedActivityResponse dar) {
                ActivityRecognitionResult arr = dar.getActivityRecognitionResult();
                // getMostProbableActivity() is good enough for basic Activity detection.
                // To work within a threshold of confidence,
                // use ActivityRecognitionResult.getProbableActivities() to get a list of
                // potential current activities, and check the confidence of each one.
                DetectedActivity probableActivity = arr.getMostProbableActivity();

                int confidence = probableActivity.getConfidence();
                String activityStr = probableActivity.toString();
                mLogFragment.getLogView().println("Activity: " + activityStr
                    + ", Confidence: " + confidence + "/100");
            }
        })

ขั้นตอนถัดไป

ดูข้อมูลเพิ่มเติมเกี่ยวกับ API ต่างๆ ภายใน Awareness API