eticaretteyim

Add Voice Interactions to Your E-Commerce Mobile App

Search & Directory Engines eticaretteyim Yönetici Published: Last updated: 11 min read
Share: Link copied
E-commerce packages
Search & Directory Engines eticaretteyim Yönetici
  • Published:
  • Last updated:
  • 11 min read
Share:
Link copied

With today's evolving technology, a number of different strategies are needed. As many of you know, voice navigation and voice search have now started on computers, tablets, phones and other smart devices. One of the things e-commerce site managers should also take into account is that people no longer bother typing on the keys of the search bar; instead, they press the Voice button and search by speaking. Is your e-commerce site or your e-commerce mobile app ready for this technology? (Please implement the code and forms below together with your professional developer!)

In this code lab, you will learn how to add voice interactions to your app using the Voice Interaction API. The Voice Interaction API allows your app's users to confirm actions and choose from a list of options using only their voices.

What You Will Learn

  • Updating the Android manifest to support voice actions.
  • Triggering a voice confirmation in your app.
  • Adding custom synonyms for voice confirmations.

Requirements

  • Android Studio version 1.0+
  • Sample code.
  • Google app version 5+
  • A test device with the Android M Preview feature.
  • A USB micro-USB cable.

Download the Sample Code

You can download the entire sample code to your computer ...

Download the zip

... or clone the GitHub repository from the command line.

io2015-codelabs repository contains many sample projects. This codelab uses only one of them:

  • voice interactions — This Voice Interactions codelab.

#2. Try the Voice Interaction

Warning: The "Take a selfie" step may require several attempts before it starts working. This is a known configuration issue.

Let's start by trying the finished sample. This will help show what we are doing, and will show you the interaction between the Google app and your own app.

  1. Select the directory from your sample code download (File > Import Project… > voice-interaction-end).
  2. Click the Gradle sync button.
  3. Click the Run button.
  4. Open the Google app.
  5. Say "OK Google."
  6. When the voice prompt appears, say "Take a selfie." Remember: because of a known configuration issue, you may need to try this a few times before it starts working.
  7. The Voice Camera app should open and ask you to take a photo.
  8. Respond with "Cheese."

That's it! You've taken your first selfie that works by voice using the Voice Interaction API.

Frequently Asked Questions

  • How do I install Android Studio?
  • How do I enable USB debugging?
  • Why doesn't Android Studio see my device?
  • Android error: Failed to install * .apk on device *: timeout?

#3 Build the starter app

Now let's open the starter app and learn how to add voice interaction to it so that it has all the features you saw in the finished sample app.

  1. Select the directory from your sample code download (File > Import Project… > voice-interaction-start).
  2. Click the Gradle sync button.
  3. Click the Run button.

After a few seconds you will see a camera app. That is all our app does so far. In the following steps, we will add voice interaction to this starter app.

#4. Migrate the app to the Android M Preview

The first thing you need to do to prepare your project for the Voice Interaction API is update your Gradle build settings to use Android M.

Application / build.gradle

compileSdkVersion "android-MNC"
buildToolsVersion "21.1.1"

defaultConfig

{
minSdkVersion "android-MNC"
targetSdkVersion "android-MNC"
}

After changing your build settings, be sure to perform a Gradle sync.

Frequently Asked Questions

  • How can I get the Android M Preview SDK?

#5. Add a voice interaction intent

Now it's time to add some voice intents to your app. We will use android.media.action.IMAGE_CAPTURE and android.media.action.STILL_IMAGE_CAMERA, which are system actions already supported on Android.

In Application / src / main / AndroidManifest.xml

<activity
    android:name="com.example.android.voicecamera.TakePictureActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.media.action.IMAGE_CAPTURE" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.VOICE" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.media.action.STILL_IMAGE_CAMERA" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.VOICE" />
    </intent-filter>
</activity>

Note that both intents must declare the android.intent.category.VOICE and android.intent.category.DEFAULT categories so that they can be called by the Voice Interaction API.

Note: The DEFAULT category is required for the Android intent resolution to work successfully. The Google app always prefers a voice interaction over a non-voice interaction when the user interacts by voice.

#6 Handle the voice interaction intents

After you have defined some voice intents for your app, you need to add an activity to handle them.

Create a new class called TakePictureActivity in the package and add the following code to the com.example.android.voicecamera package.

TakePictureActivity.java

package com.example.android.voicecamera;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class TakePictureActivity extends Activity {
private static String TAG = "TakePictureActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: ");
Intent intent = getIntent();
if (intent == null) {
finish();
} else if (CameraActivity.needPermissions(this)) {
startActivity(new Intent(this, CameraActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
return;
} else if (!isVoiceInteraction()) {
Log.e(TAG, "Not voice interaction");
if (intent != null) {
intent.setComponent(null);
intent.setPackage("com.google.android.GoogleCamera");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
finish();
return;
}

setContentView(R.layout.activity_camera);
CameraFragment fragment = CameraFragment.newInstance();
fragment.setArguments(getIntent().getExtras());

getFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
}

In this activity, you can see that the onCreate() method examines the intent that triggered the activity, and looks for a voice interaction intent using the isVoiceInteraction() helper method. You will also notice that it checks whether camera permissions are required. This is another new feature that allows apps on Android M to request new permissions at runtime.

If all checks succeed, the activity shows the CameraFragment. In a few steps, you will see how we add voice interaction to that fragment.

#7. Request camera permissions

In the previous step you saw how TakePictureActivity checks camera permissions and redirects the user to CameraActivity if they are not found.

You need to make some changes so that CameraActivity lets the user grant app permissions at runtime. First, add a few imports to the file:

CameraActivity.java

import android.Manifest;
import android.content.pm.PackageManager;
import android.provider.MediaStore;
import android.widget.Toast;

CameraActivity.java

private static final int PERMISSIONS_REQUEST_ALL_PERMISSIONS = 1;
private Bundle mSavedInstanceState;

CameraActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();

if (needPermissions(this)) {
requestPermissions();
} else if (intent != null) {
intent.setComponent(null);
intent.setPackage("com.google.android.GoogleCamera");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
finish();
}
}

CameraActivity.java

static public boolean needPermissions(Activity activity) {
    Log.d(TAG, "needPermissions: ");
    return activity.checkSelfPermission(Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED
            || activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED;
}

CameraActivity.java

private void requestPermissions() {
    Log.d(TAG, "requestPermissions: ");
    String[] permissions = new String[] {
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    requestPermissions(permissions, PERMISSIONS_REQUEST_ALL_PERMISSIONS);
}

When requestPermissions() completes, it will call back to the onRequestPermissionsResult method, where you need to record whether all permissions were granted.

CameraActivity.java

public void onRequestPermissionsResult(int requestCode, String permissions[],
                                           int[] grantResults) {
    switch (requestCode) {
        case PERMISSIONS_REQUEST_ALL_PERMISSIONS:
            boolean hasAllPermissions = true;
            for (int i = 0; i < grantResults.length; ++i) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    hasAllPermissions = false;
                    Log.e(TAG, "Unable to get permission " + permissions[i]);
                }
            }
            if (hasAllPermissions) {
                finish();
            } else {
                Toast.makeText(this,
                        "Unable to get all required permissions", Toast.LENGTH_LONG).show();
                finish();
                return;
            }
            break;
        default:
            Log.e(TAG, "Unexpected request code");
    }
}

Now you have made sure your app can access the camera, and if it cannot, the user is asked whether they want to give your app access to the camera.

#8. Implement "Say cheese" to take a photo

Now let's get to the fun part: defining the voice interaction between your app and the assistant. First, we will add some imports.

CameraFragment.java

import android.app.VoiceInteractor;
import android.app.VoiceInteractor.PickOptionRequest;
import android.app.VoiceInteractor.PickOptionRequest.Option;
import android.view.Gravity;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;

After the assistant captures the user's response, focus returns to your app and you can continue taking the photo. To do this, add an if statement at the end of your onResume() method that checks for a voice interaction. If one is found, it checks whether a timer was specified and calls startVoiceTimer(); otherwise it calls the startVoiceTrigger() method.

CameraFragment.java

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume: ");
    startBackgroundThread();

// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
// a camera and start preview from here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}

if (mOrientationListener.canDetectOrientation()) {
mOrientationListener.enable();
}

if (getActivity().isVoiceInteraction()) {
if (isTimerSpecified()) {
startVoiceTimer();
} else {
startVoiceTrigger();
}
}
}

Now create the startVoiceTrigger() method. Create the voice interaction using the VoiceInteractor from the activity. As you can see, you can easily customize the Option presented to the user. Add synonyms for "cheese", "ready", "go", "take" and "ok".

CameraFragment.java

private void startVoiceTrigger() {
    Log.d(TAG, "startVoiceTrigger: ");
    Option option = new Option("cheese");
    option.addSynonym("ready");
    option.addSynonym("go");
    option.addSynonym("take it");
    option.addSynonym("ok");

getActivity

().getVoiceInteractor()
.submitRequest(new PickOptionRequest("Say Cheese", new Option[]{option}, null) {
@Override
public void onPickOptionResult(boolean finished, Option[] selections, Bundle result) {
if (finished && selections.length == 1) {
Message message = Message.obtain();
message.obj = result;
takePicture();
} else {
getActivity().finish();
}
}
@Override
public void onCancel() {
getActivity().finish();
}
});
}

If the user chooses to use any of these synonyms for the Option, the takePicture() method is called; otherwise, we exit the activity.

#9. Add voice interaction to the camera

The next step is to add voice interaction capabilities to your camera fragment. First, add the newInstance() method, which helps create new instances of this fragment.

CameraFragment.java

public static CameraFragment newInstance() {
    Log.d(TAG, "newInstance: ");
    CameraFragment fragment = new CameraFragment();
    fragment.setRetainInstance(true);
    return fragment;
}

In the onCreateView() method, you need to check for voice interactions and hide the camera controls while the user is interacting by voice.

CameraFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView: ");
    View view = inflater.inflate(R.layout.fragment_camera2_basic, container, false);
    if (getActivity().isVoiceInteraction()) {
        View controls = view.findViewById(R.id.controls);
        if (controls != null) {
            controls.setVisibility(View.GONE);
        }
    }
    return view;
}

Finally, we will improve the showToast() method so that it not only shows a visual confirmation that a photo was taken, but also confirms it by voice, saying "Here it is".

CameraFragment.java

private void showToast(String text) {
    // We show a Toast by sending request message to mMessageHandler. This makes sure that the
    // Toast is shown on the UI thread.
    Activity activity = getActivity();
    if (activity.isVoiceInteraction()) {
        Message message = Message.obtain();
        message.obj = text;
        //mSharingHandler.sendMessage(message);

Uri contextUri = Uri.fromFile(mFile);
Log.e(TAG, "PHOTO URI: " + contextUri);
Log.e(TAG, "PHOTO LOCATION: " + mFile.getAbsolutePath());
Log.e(TAG, "showToast:" + Log.getStackTraceString(new Exception()));

Bundle extras = new Bundle();
extras.putParcelable("context_uri", contextUri);
activity.getVoiceInteractor().submitRequest(
new VoiceInteractor.CompleteVoiceRequest("Here it is", extras) {
@Override
public void onCompleteResult(Bundle result) {
super.onCompleteResult(result);
Log.d(TAG, "OnCompleteResult:" + Log.getStackTraceString(new Exception()));
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + mFile.getAbsolutePath()), "image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().finish();
startActivity(intent);
}
});
} else {
Message message = Message.obtain();
message.obj = text;
mMessageHandler.sendMessage(message);
}
}

The camera fragment is now ready to handle voice interactions.

#10. Add a countdown timer

When taking photos hands-free with the camera, it helps to have a countdown so that you know when to smile. First, you need to add a few features to CameraFragment.

CameraFragment.java

private static final String EXTRA_TIMER_DURATION_SECONDS = "android.intent.extra.TIMER_DURATION_SECONDS";

private TextView mTimerCountdownLabel = null;
private Toast mTimerCountdownToast = null;

Next, you need to add the startVoiceTimer() method to create the toast and start the timer.

CameraFragment.java

private void startVoiceTimer() {
    Log.d(TAG, "startVoiceTimer: ");
    final int countdown = getArguments().getInt(EXTRA_TIMER_DURATION_SECONDS);

mTimerCountdownToast

= new Toast(getActivity().getApplicationContext());
mTimerCountdownToast.setGravity(Gravity.CENTER, 0, 0);
mTimerCountdownToast.setDuration(Toast.LENGTH_SHORT);

LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_timer,
(ViewGroup) getActivity().findViewById(R.id.toast_layout_root));
mTimerCountdownToast.setView(layout);
final TextView label = (TextView) layout.findViewById(R.id.countdown_text);

Timer timer = new Timer("camera_timer");
timer.scheduleAtFixedRate(new TimerTask() {
private int mCountdown = countdown;

@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (mCountdown < 0) {
Log.e(TAG, "Take photo: " + mCountdown);
mTimerCountdownToast.cancel();
takePicture();
} else {
Log.e(TAG, "Execute timer: " + mCountdown);
label.setText(String.format("Photo in %d", mCountdown));
mTimerCountdownToast.show();
}
}
});
mCountdown--;
if (mCountdown < 0) {
cancel();
}
}
}, 1000, 1000);
}

We also need to create a helper method to check whether a timer has been specified.

CameraFragment.java

private boolean isTimerSpecified() {
    Log.d(TAG, "isTimerSpecified: ");
    return getArguments() != null && getArguments().containsKey(EXTRA_TIMER_DURATION_SECONDS);
}

That is all the code you need to add. There are a few layouts to add, and you're done!

#11. Update the user interface

We need to make some updates to the user interface. First, let's create a layout for MainActivity. This is a very simple layout that shows a TextView with the intro message.

layout / activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<LinearLayout style="@style/Widget.SampleMessageTile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView style="@style/Widget.SampleMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/horizontal_page_margin"
android:layout_marginRight="@dimen/horizontal_page_margin"
android:layout_marginTop="@dimen/vertical_page_margin"
android:layout_marginBottom="@dimen/vertical_page_margin"
android:text="@string/intro_message" />
</LinearLayout>
</LinearLayout>

We also need to create a layout that displays the countdown for the toast. It looks like this:

layout / toast_timer.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:background="@drawable/bg_toast"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp">
    <TextView
        android:id="@+id/countdown_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>

And that's it, we are ready to take photos with just our voice.

#12. Test the voice interaction

Now you test your app to make sure the voice interaction works correctly.

  1. Click the Gradle sync button.
  2. Click the Run button.
  3. Open the Google app.
  4. Say "OK Google."
  5. When the voice prompt appears, say "Take a selfie."
  6. The Voice Camera app should open and ask you to take a photo.
  7. Respond with "Cheese."

That's it! Using the Voice Interaction API, you have built your first voice-enabled camera app and taken a rather sweet photo.

#13. Congratulations!

Your app is now ready to support voice interaction in your app. As you can see, there are many areas where a hands-free interface like this can make your app easier to use and more fun for users.

What we covered

  • Updated the Android manifest to support voice actions.
  • Triggered a voice confirmation in your app.
  • Added custom synonyms for voice confirmations.

Next steps

  • Add voice interaction to your own app.
  • Read the list of system actions to see which voice actions are already built into Android.
  • Learn about creating custom voice actions.

If you want to learn more about the Voice Interaction API, please see the developer documentation.

You can post questions and find answers on Stack Overflow under the google-search tag. Source: codelabs.developers.google.com

You can get support from us if you get stuck.

eticaretteyim Yönetici

We create easy-to-follow guides for store owners on e-commerce, hosting and business email.

Was this post helpful?

Comments

No comments yet. Be the first to comment.

Leave a comment

Comments are published after approval. Your email address is never shown on the site.

Related posts

Hi! If you need any help, we’re here.