Question

My app uses a microphone(AudioRecord) in a background mode,How to make the listener for phone events and voice commands (like google voice). It is necessary for me to release a microphone(AudioRecord) for use.

I found a solution to phone events: http://www.botskool.com/geeks/how-listen-phone-events-android. to use: TelephonyManager , PhoneStateListener.

But not to voice commands. Help pls.

Was it helpful?

Solution

There is no specific way you can do this (unfortunately) and it will only be the application that attempts to use the mic resource that will get an error.

What you can do is monitor what the user is doing in the background and react accordingly. Here is the code to check if Google Now has become the foreground application:

public static boolean googleNowForeground(final Context ctx) {

    final ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);

    if (activityManager.getRunningTasks(1).get(0) != null) {

        final PackageManager pm = ctx.getPackageManager();

        try {
            final PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(
                    activityManager.getRunningTasks(1).get(0).topActivity.getPackageName(), 0);

            if (foregroundAppPackageInfo != null) {

                if (foregroundAppPackageInfo.packageName.matches(Constants.GOOGLE_NOW_PACKAGE_NAME)) {
                    return true;
                }
            }

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    return false;
}

This is the least 'expensive' way I've found to perform such actions, but the method above is not guaranteed to be called in future OS versions, not to mention having to hard-code the package names you are concerned with....

The 'expense' of monitoring for foreground applications that you know will conflict with your application may be somewhat minimal in comparison to permanently recording audio, but you should code your implementation wisely to minimise the monitor within certain device condition parameters.

I've investigated other methods to monitor intent broadcasts that are associated with mic resources, but they've been less successful than the above.

Requesting that the user create an 'exclude list' for the conflicting applications will allow you to dynamically monitor if they become the foreground application and react accordingly.

Hope that helps....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top