新增 AppIndexing API
對於將此新增到專案中,你可以輕鬆找到官方文件,但在此示例中,我將重點介紹一些需要注意的關鍵區域。
第 1 步: - 新增谷歌服務
dependencies {
...
compile 'com.google.android.gms:play-services-appindexing:9.4.0'
...
}
第 2 步: - 匯入類
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
第 3 步: - 新增 App Indexing API 呼叫
private GoogleApiClient mClient;
private Uri mUrl;
private String mTitle;
private String mDescription;
//If you know the values that to be indexed then you can initialize these variables in onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
mUrl = "http://examplepetstore.com/dogs/standard-poodle";
mTitle = "Standard Poodle";
mDescription = "The Standard Poodle stands at least 18 inches at the withers";
}
//If your data is coming from a network request, then initialize these value in onResponse() and make checks for NPE so that your code won’t fall apart.
//setting title and description for App Indexing
mUrl = Uri.parse(“android-app://com.famelive/https/m.fame.live/vod/” +model.getId());
mTitle = model.getTitle();
mDescription = model.getDescription();
mClient.connect();
AppIndex.AppIndexApi.start(mClient, getAction());
@Override
protected void onStop() {
if (mTitle != null && mDescription != null && mUrl != null) //if your response fails then check whether these are initialized or not
if (getAction() != null) {
AppIndex.AppIndexApi.end(mClient, getAction());
mClient.disconnect();
}
super.onStop();
}
public Action getAction() {
Thing object = new Thing.Builder()
.setName(mTitle)
.setDescription(mDescription)
.setUrl(mUrl)
.build();
return new Action.Builder(Action.TYPE_WATCH)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
要測試這一點,請按照下面給出的備註中的步驟 4 進行測試。