Tài liệu này giải thích cách bắt đầu phát triển bằng Awareness API trên Android. Awareness API là một phần của Dịch vụ Google Play.
Để sử dụng Awareness API, bạn cần có Tài khoản Google. Nếu đã có tài khoản thì bạn có thể bỏ qua bước này. Bạn cũng nên có một Tài khoản Google riêng cho mục đích thử nghiệm.
Trước khi bắt đầu
Lấy khoá API
Nếu bạn chưa bật Awareness API và chưa lấy khoá API của Google, hãy làm theo các bước trong phần Đăng ký và khoá API để thực hiện.
Định cấu hình ứng dụng
Trong tệp
build.gradle
cấp dự án, hãy thêm kho lưu trữ Maven của Google vào cả hai mụcbuildscript
vàallprojects
:buildscript { repositories { google() } } allprojects { repositories { google() } }
Thêm các phần phụ thuộc cho Awareness API vào tệp Gradle cấp ứng dụng của mô-đun, thường là
app/build.gradle
:dependencies { implementation 'com.google.android.gms:play-services-awareness:19.1.0' }
Thêm Khoá API Awareness vào tệp
AndroidManifest.xml
của ứng dụng. Để làm như vậy, hãy thêm thẻ<meta-data>
bằngandroid:name="com.google.android.awareness.API_KEY"
. Đối vớiandroid:value
, hãy chèn Khoá API Nhận biết của riêng bạn trong dấu ngoặc kép.<manifest> <application> <meta-data android:name="com.google.android.awareness.API_KEY" android:value="API_KEY"/> </application> </manifest>
Thêm các quyền cần thiết vào tệp
AndroidManifest.xml
của ứng dụng. Các quyền bắt buộc sẽ khác nhau, tuỳ thuộc vào phương thức API và loại hàng rào mà ứng dụng của bạn sử dụng.
Ví dụ về lệnh gọi
Ví dụ sau đây minh hoạ cách sử dụng mô hình dịch vụ Google Play không có kết nối với Awareness API:getDetectedActivity()
// 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");
}
})
Các bước tiếp theo
Tìm hiểu thêm về các API trong Awareness API: