+2

Google Play Service 7.5.x có gì mới ?

Tại sự kiện Google IO năm nay, Google giới thiệu phiên bản Google Play Service 7.5.0 gồm nhiều tính năng mới và hấp dẫn Và trong tháng này Google phát hành thư viện mới nhất này cho các lập trình Viên. Vậy nó có điểm gì đổi mởi so với version cũ.

Trước tiên phải để đến

Smart Lock for Passwords alt

Với một tài khoản Google bạn có thể lưu trữ mọi mật khẩu của mọi ứng dụng hoặc website và đồng bộ dữ liệu với các thiết bị của bạn

Với Android để sử dụng ta cần thông qua Credentials API

Lưu thông tin người dùng

Auth.CredentialsApi.save(mCredentialsClient, credential).setResultCallback(
  new ResultCallback() {
      @Override
      public void onResult(Status status) {
          if (status.isSuccess()) {
              // Credentials were saved
          } else {
              if (status.hasResolution()) {
                  // Try to resolve the save request. This will prompt the user if
                  // the credential is new.
                  try {
                      status.startResolutionForResult(this, RC_SAVE);
                  } catch (IntentSender.SendIntentException e) {
                      // Could not resolve the request
                  }
              }
          }
      }
  });

Khôi phục thông tin người dùng

Auth.CredentialsApi.request(mCredentialsClient, mCredentialRequest).setResultCallback(
  new ResultCallback() {
      @Override
      public void onResult(CredentialRequestResult credentialRequestResult) {
          if (credentialRequestResult.getStatus().isSuccess()) {
              // Handle successful credential requests
          } else {
              // Handle unsuccessful and incomplete credential requests
          }
      }
  });

Instance ID, Identity, and Authorization Từ phiên bản mới này ngoài việc hỗ trợ Android chính thì cũng hỗ trợ nền tảng iOS nữa Vì thế với mỗi 1 Instance ID định danh cho một người dùng Android hay iOS

alt

Google Cloud Messaging

Ngoài việc version mới này đã hỗ trợ thêm cho iOS thì Google phát hành nhiều API mới giúp lập trình dễ dàng quản lý hiệu suất và hiệu năng

Điểm mới khi cài đặt là ta cần một token thông qua Instance ID

String authorizedEntity = PROJECT_ID; // Project id from Google Developers Console
String scope = “GCM”; // e.g. communicating using GCM, but you can use any
                      // URL-safe characters up to a maximum of 1000, or
                      // you can also leave it blank.
String token = InstanceID.getInstance(context).getToken(authorizedEntity,scope);

Để xóa

String authorizedEntity = PROJECT_ID;
String scope = “GCM”;
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

Thật sự là đã rất gắn ngọn hơn nhiều so với trước

Các bạn cũng biết với phiên bản cũ một GCM token thường có timeout khoảng 2 tuần, trước khi nó die nó chỉ thông báo qua api phía server, và client thực sự không check được điều này. Nên thường daax tới không hay cập nhật lại token này Về phiên bản mới này Google cho phép client check điều đó thông qua InstanceIDListenerService

public class MyInstanceIDService extends InstanceIDListenerService {
  public void onTokenRefresh() {
    refreshAllTokens();
  }

  private void refreshAllTokens() {
    // assuming you have defined TokenList as
    // some generalized store for your tokens
    ArrayList<TokenList> tokenList = TokensList.get();
    InstanceID iid = InstanceID.getInstance(this);
    for(tokenItem : tokenList) {
      tokenItem.token =
        iid.getToken(tokenItem.authorizedEntity,tokenItem.scope,tokenItem.options);
      // send this tokenItem.token to your server
    }
  }
};

.........

<service android:name=".MyInstanceIDService" android:exported="false">
  <intent-filter>
        <action android:name="com.google.android.gms.iid.InstanceID"/>
  </intent-filter>
</service>

Thực sự việc bắt message trên bản cũ phức tạp. Biên bản mới thì mọi sự kiện từ gửi, nhận, xóa, .... đều nằm trong GcmListenerService

Ví dụ nhận một message

@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);

    sendNotification(message);
}

Topic based subscriptions Ngoài chức năng GCM thông thường thì phiên bản mới hỗ trợ việc theo dõi một chủ đề nào đó. Ví dụ như User theo dõi mọi campaign nào đó trên Ứng dụng của mình và khi có Campaign bắt đầu hoặc kết thúc User sẽ nhận được thông báo Ví dụ để đăng ký 1 topic

GcmPubSub.getInstance(context).subscribe(regToken, "/topics/[yourTopic]", null);

Kỳ vọng nhất lần update lần này của lập trình viên đó chính là GCM Network Manager Cho phép ứng dụng thực hiện các tác vụ liên quan đến mạng theo các tiêu chí sau: (Không dịch mấy câu TA đầu mục sợ sai nghĩa)

  • Schedule one-off vs. periodic tasks. Đăng ký tác vụ chạy một lần hoặc lặp lại với API đơn giản
  • Automatic back-off and failure retry. Nếu như nhiệm vụ thất bại như mất mạng.... thì tự động chạy lại
  • Awareness of network activity. Xác định thời điểm tối ưu nhất để chạy -> đại khái để tiết kiệm pin và tăng hiệu suất
  • Awareness of device charging state.Một số tác vụ có thể cài đặt chỉ chạy khi thiết bị đang ở chế độ sạc pin
  • Persistence of tasks across boot. Tác vụ có thể chạy ngay sau khi máy được khởi động hoặc app được bật lần đầu tiên
  • Ease of implementation/refactoring of existing code

Cài đặt Tạo 1 service và implement GcmTaskService

<service android:name="com.example.MyTaskService"
              android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE"
              android:exported="true">
    <intent-filter>
            <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY"/>
    </intent-filter>
</service>

Ví dụ các tạo một tác vụ chạy một lần chỉ khi có mạng và đang sạc pin

long startSecs = 0L; // allow for execution of the task as soon as possible (0s from now)

long endSecs = startSecs + 3600L; // task will be run within 1 min of start time

string tag = "oneoff  | " + taskID++ + ": [" + startSecs + "," + endSecs + "]"; // a unique task identifier

OneoffTask oneoff = new OneoffTask.Builder()
                .setService(<your service>)
                .setTag(tag)
                .setExecutionWindow(startSecs, endSecs)
                .setRequiredNetwork(com.google.android.gms.gcm.Task.NETWORK_STATE_CONNECTED)
                .setRequiresCharging(true)
                .build();
        mScheduler.schedule(oneoff);

Ví dụ các tạo một tác vụ chạy định kì khi có mạng và đang sạc pin

long periodSecs = 30L; // the task should be executed every 30 seconds

long flexSecs = 15L; // the task can run as early as -15 seconds from the scheduled time

string tag = "periodic  | " + taskID++ + ": " + periodSecs + "s, f:" + flexSecs;  // a unique task identifier

PeriodicTask periodic = new PeriodicTask.Builder()
                .setService(<your service>)
                .setPeriod(periodSecs)
                .setFlex(flexSecs)
                .setTag(tag)
                .setPersisted(true)
                .setRequiredNetwork(com.google.android.gms.gcm.Task.NETWORK_STATE_ANY)
                .setRequiresCharging(false)
                .build();
        mScheduler.schedule(periodic);

App Invites Beta Tính năng mới này vẫn chỉ đang Beta nhưng cũng khá hay Đó là cho phép gửi lời mời sử dụng ứng dụng thông qua SMS hoặc gửi email cho bạn bè

Đây là bải viết mang hơi hướng giới thiệu là chính. Hi vọng sẽ sớm có bài viết chuyên sâu sử dụng các API mới này


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí