เอกสารนี้อธิบายวิธีเริ่มต้นพัฒนาด้วย Awareness API ใน Android โดย Awareness API เป็นส่วนหนึ่งของ บริการ Google Play
หากต้องการใช้ Awareness API คุณต้องมีบัญชี Google หากมีบัญชีอยู่แล้ว คุณก็พร้อมใช้งานได้ นอกจากนี้ คุณอาจต้องการบัญชี Google แยกต่างหากเพื่อวัตถุประสงค์ในการทดสอบด้วย
ก่อนเริ่มต้น
รับคีย์ API
หากยังไม่ได้เปิดใช้ Awareness API และรับคีย์ API ของ Google ให้ทำตามขั้นตอนในส่วนการลงชื่อสมัครใช้และคีย์ API
กำหนดค่าแอป
ในไฟล์
build.gradleระดับโปรเจ็กต์ ให้ใส่ที่เก็บ Maven ของ Google ไว้ในทั้งส่วนbuildscriptและallprojectsดังนี้buildscript { repositories { google() } } allprojects { repositories { google() } }เพิ่มทรัพยากร Dependency สำหรับ Awareness API ลงในไฟล์ Gradle ระดับแอปของโมดูล ซึ่งโดยปกติจะเป็นไฟล์
app/build.gradleดังนี้dependencies { implementation 'com.google.android.gms:play-services-awareness:20.0.0' }เพิ่มคีย์ 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>
เพิ่มสิทธิ์ที่จำเป็นลงในไฟล์
AndroidManifest.xmlของแอป สิทธิ์ที่จำเป็นจะแตกต่างกันไปตามเมธอด API และประเภท Fence ที่แอปใช้
ตัวอย่างการเรียก
ตัวอย่างการเรียกต่อไปนี้ไปยัง
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 ได้ที่