こんにちは、KID.Aです。
今回の記事はGoogleのVoice ActionsのSystem Voice Actionsの実装方法と実行結果について記載していこうと思います。
Voice Actionsはユーザが音声コマンドでアプリを利用できるようにすることができます。
Voice Actions
説明は以下の開発サイトになります。
・Voice Actionsの開発サイト
https://developers.google.com/voice-actions/
System Voice Actions
Googleの音声操作は会話を認識してAndroidのインテントを発行します。アプリはアクションのサポートを宣言することができます。
具体的なイメージはGoogle Nowで検索された際に特定のキーワードがあれば暗黙的intentを発行してくれます。実装は暗黙intentのアクションを設定するのと、受取り側を作るだけです。
・System Voice actionsの実装ガイド
https://developers.google.com/voice-actions/system/
実装
AndroidManifest.xmlに以下のように加えます。
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".AlarmActivity"> <intent-filter> <action android:name="android.intent.action.SET_ALARM"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> </application>
ソースは暗黙的intentを受け取る実装をします。
public class AlarmActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm); Intent intent = getIntent(); if (AlarmClock.ACTION_SET_ALARM.equals(intent.getAction())) { if (intent.hasExtra(AlarmClock.EXTRA_HOUR)) { int hour = intent.getIntExtra(AlarmClock.EXTRA_HOUR, 0); // set Alarm } } } }
実行
実行する前に以下の処理をして、検索言語と音声を英語にしてください。
Googleアプリを立ち上げます。
設定 > 検索言語をEnglish(US)にします。
これで準備は完了です。実行してみましょう。
「set an Alarm for 4 a.m.」と発呼します。
そうすると、暗黙的intentが送られてandroid.intent.action.SET_ALARMが設定されているアプリが選ばれます。
設定したアプリが立ち上がると下記のフローに通ります。
if (AlarmClock.ACTION_SET_ALARM.equals(intent.getAction())) { if (intent.hasExtra(AlarmClock.EXTRA_HOUR)) { int hour = intent.getIntExtra(AlarmClock.EXTRA_HOUR, 0); // set Alarm } }
System Actionsはアラーム、電話、フィットネス、メディア(カメラやビデオ)、検索など多く用意されています。
・一覧
https://developers.google.com/voice-actions/system/#system_actions_reference
今後のOSが上がるたびに音声コマンドは増えていくと思いますのでチェックしていると新しい発見があるかもしれないです。